<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="原创,Node,Koa,Mysql,javascript," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="Koa2-blogNode+Koa2+Mysql 搭建简易博客 预览地址http://blog.wclimb.site 写在前面本篇教程一方面是为了自己在学习的过程加深记忆，也是总结的过程。另一方面给对这方面不太了解的同学以借鉴经验。如发现问题还望指正，如果你觉得这篇文章帮助到了你，那就赏脸给个star吧，https://github.com/wclimb/Koa2-blog下一篇可能是 Node">
<meta name="keywords" content="原创,Node,Koa,Mysql,javascript">
<meta property="og:type" content="article">
<meta property="og:title" content="Node+Koa2+Mysql 搭建简易博客">
<meta property="og:url" content="http://yoursite.com/2017/07/12/Node-Koa2-Mysql-搭建简易博客/index.html">
<meta property="og:site_name" content="Blog by wclimb">
<meta property="og:description" content="Koa2-blogNode+Koa2+Mysql 搭建简易博客 预览地址http://blog.wclimb.site 写在前面本篇教程一方面是为了自己在学习的过程加深记忆，也是总结的过程。另一方面给对这方面不太了解的同学以借鉴经验。如发现问题还望指正，如果你觉得这篇文章帮助到了你，那就赏脸给个star吧，https://github.com/wclimb/Koa2-blog下一篇可能是 Node">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://oswpupqu5.bkt.clouddn.com/blog.gif">
<meta property="og:image" content="http://yoursite.com/img/database.png">
<meta property="og:image" content="http://yoursite.com/img/tables.png">
<meta property="og:image" content="http://yoursite.com/img/item.png">
<meta property="og:image" content="http://yoursite.com/img/view.png">
<meta property="og:image" content="http://yoursite.com/img/signup.png">
<meta property="og:image" content="http://yoursite.com/img/users.png">
<meta property="og:updated_time" content="2017-07-28T09:30:44.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Node+Koa2+Mysql 搭建简易博客">
<meta name="twitter:description" content="Koa2-blogNode+Koa2+Mysql 搭建简易博客 预览地址http://blog.wclimb.site 写在前面本篇教程一方面是为了自己在学习的过程加深记忆，也是总结的过程。另一方面给对这方面不太了解的同学以借鉴经验。如发现问题还望指正，如果你觉得这篇文章帮助到了你，那就赏脸给个star吧，https://github.com/wclimb/Koa2-blog下一篇可能是 Node">
<meta name="twitter:image" content="http://oswpupqu5.bkt.clouddn.com/blog.gif">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/07/12/Node-Koa2-Mysql-搭建简易博客/"/>





  <title>Node+Koa2+Mysql 搭建简易博客 | Blog by wclimb</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Blog by wclimb</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/07/12/Node-Koa2-Mysql-搭建简易博客/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="wclimb">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Blog by wclimb">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Node+Koa2+Mysql 搭建简易博客</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-12T14:23:15+08:00">
                2017-07-12
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/javascript/" itemprop="url" rel="index">
                    <span itemprop="name">javascript</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/javascript/node/" itemprop="url" rel="index">
                    <span itemprop="name">node</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>   浏览
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="Koa2-blog"><a href="#Koa2-blog" class="headerlink" title="Koa2-blog"></a>Koa2-blog</h2><p>Node+Koa2+Mysql 搭建简易博客</p>
<h2 id="预览地址"><a href="#预览地址" class="headerlink" title="预览地址"></a>预览地址</h2><p><a href="http://blog.wclimb.site" target="_blank" rel="external">http://blog.wclimb.site</a></p>
<h2 id="写在前面"><a href="#写在前面" class="headerlink" title="写在前面"></a>写在前面</h2><p>本篇教程一方面是为了自己在学习的过程加深记忆，也是总结的过程。另一方面给对这方面不太了解的同学以借鉴经验。如发现问题还望指正，<br>如果你觉得这篇文章帮助到了你，那就赏脸给个star吧，<a href="https://github.com/wclimb/Koa2-blog" target="_blank" rel="external">https://github.com/wclimb/Koa2-blog</a><br>下一篇可能是 Node + express + mongoose 或 zepto源码系列<br>感谢您的阅读^_^<br>ps：关于markdown代码缩进问题，看起来不太舒服，但复制到编辑器是正常的哟！</p>
<h2 id="演示效果"><a href="#演示效果" class="headerlink" title="演示效果"></a>演示效果</h2><p><img src="http://oswpupqu5.bkt.clouddn.com/blog.gif" alt="img"></p>
<h2 id="开发环境"><a href="#开发环境" class="headerlink" title="开发环境"></a>开发环境</h2><ul>
<li>nodejs <code>v8.1.0</code></li>
<li>koa <code>v2.3.0</code></li>
<li>mysql <code>v5.7.0</code></li>
</ul>
<h2 id="准备工作"><a href="#准备工作" class="headerlink" title="准备工作"></a>准备工作</h2><p>文中用到了promise、async await等语法，所以你需要一点es6的语法，传送门当然是阮老师的教程了 <a href="http://es6.ruanyifeng.com/" target="_blank" rel="external">http://es6.ruanyifeng.com/</a> </p>
<p>如果你已经配置好node和mysql可以跳过</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ node -v   查看你的node版本，如果过低则去nodejs官网下载替换之前的版本</div></pre></td></tr></table></figure>
<p>下载mysql，并设置好用户名和密码，默认可以为用户名：root，密码：123456</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">进入到 bin 目录下 比如 cd C:\Program Files\MySQL\MySQL Server 5.7\bin</div></pre></td></tr></table></figure>
<p>然后开启mysql<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ mysql -u root -p</div></pre></td></tr></table></figure></p>
<p>输入密码之后创建<code>database</code>(数据库)，<code>nodesql</code>是我们创建的数据库<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ create database nodesql;</div></pre></td></tr></table></figure></p>
<p>记住sql语句后面一定要跟<code>;</code>符号，接下来看看我们创建好的数据库列表</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ show databases;</div></pre></td></tr></table></figure>
<p><img src="/img/database.png" alt="img"></p>
<p>启用创建的数据库<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ use nodesql;</div></pre></td></tr></table></figure></p>
<p>查看数据库中的表<br><a id="more"></a><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ show tables;</div></pre></td></tr></table></figure></p>
<p>显示<code>Empty set (0.00 sec)</code>，因为我们还没有建表，稍后会用代码建表<br>注释：<br>这是后面建表之后的状态<br><img src="/img/tables.png" alt="img"></p>
<h2 id="目录结构"><a href="#目录结构" class="headerlink" title="目录结构"></a>目录结构</h2><p><img src="/img/item.png" alt="img"></p>
<ul>
<li>config 存放默认文件</li>
<li>lib 存放操作数据库文件</li>
<li>middlewares 存放判断登录与否文件</li>
<li>public 存放样式文件</li>
<li>routes 存放路由文件</li>
<li>views 存放模板文件</li>
<li>index 程序主文件</li>
<li>package.json 包括项目名、作者、依赖等等</li>
</ul>
<p>首先我们创建koa2-blog文件夹，然后<code>cd koa2-blog</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">接着使用 `npm init` 来创建package.json</div></pre></td></tr></table></figure></p>
<p>接着安装包，安装之前我们使用<a href="https://npm.taobao.org/" target="_blank" rel="external">cnpm</a>安装<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ npm install -g cnpm --registry=https://registry.npm.taobao.org</div></pre></td></tr></table></figure></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ cnpm i koa koa-bodyparser koa-mysql-session koa-router koa-session-minimal koa-static koa-views md5 moment mysql ejs --save</div></pre></td></tr></table></figure>
<p>各模块用处</p>
<ol>
<li><code>koa node</code>框架</li>
<li><code>koa-bodyparser</code> 表单解析中间件</li>
<li><code>koa-mysql-session</code>、<code>koa-session-minimal</code> 处理数据库的中间件</li>
<li><code>koa-router</code> 路由中间件</li>
<li><code>koa-static</code> 静态资源加载中间件</li>
<li><code>ejs</code> 模板引擎</li>
<li><code>md5</code> 密码加密</li>
<li><code>moment</code> 时间中间件</li>
<li><code>mysql</code> 数据库</li>
<li><code>koa-views</code> 模板呈现中间件</li>
</ol>
<p>在文件夹里面新建所需文件</p>
<p><img src="/img/view.png" alt="img"></p>
<h2 id="首先配置config"><a href="#首先配置config" class="headerlink" title="首先配置config"></a>首先配置config</h2><p>我们新建<code>default.js</code>文件 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">const config = &#123;</div><div class="line">  // 启动端口</div><div class="line">  port: 3000,</div><div class="line"></div><div class="line">  // 数据库配置</div><div class="line">  database: &#123;</div><div class="line">    DATABASE: &apos;nodesql&apos;,</div><div class="line">    USERNAME: &apos;root&apos;,</div><div class="line">    PASSWORD: &apos;123456&apos;,</div><div class="line">    PORT: &apos;3306&apos;,</div><div class="line">    HOST: &apos;localhost&apos;</div><div class="line">  &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">module.exports = config</div></pre></td></tr></table></figure>
<p>这是我们所需的一些字段，包括端口和数据库连接所需，最后我们把它exports暴露出去，以便可以在别的地方使用</p>
<h2 id="配置index-js文件"><a href="#配置index-js文件" class="headerlink" title="配置index.js文件"></a>配置index.js文件</h2><p><code>index.js</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> Koa=<span class="built_in">require</span>(<span class="string">'koa'</span>);</div><div class="line"><span class="keyword">var</span> path=<span class="built_in">require</span>(<span class="string">'path'</span>)</div><div class="line"><span class="keyword">var</span> bodyParser = <span class="built_in">require</span>(<span class="string">'koa-bodyparser'</span>);</div><div class="line"><span class="keyword">var</span> ejs=<span class="built_in">require</span>(<span class="string">'ejs'</span>);</div><div class="line"><span class="keyword">var</span> session = <span class="built_in">require</span>(<span class="string">'koa-session-minimal'</span>);</div><div class="line"><span class="keyword">var</span> MysqlStore = <span class="built_in">require</span>(<span class="string">'koa-mysql-session'</span>);</div><div class="line"><span class="keyword">var</span> config = <span class="built_in">require</span>(<span class="string">'./config/default.js'</span>);</div><div class="line"><span class="keyword">var</span> router=<span class="built_in">require</span>(<span class="string">'koa-router'</span>)</div><div class="line"><span class="keyword">var</span> views = <span class="built_in">require</span>(<span class="string">'koa-views'</span>)</div><div class="line"><span class="keyword">var</span> koaStatic = <span class="built_in">require</span>(<span class="string">'koa-static'</span>)</div><div class="line"><span class="keyword">var</span> app=<span class="keyword">new</span> Koa()</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">// session存储配置</span></div><div class="line"><span class="keyword">const</span> sessionMysqlConfig= &#123;</div><div class="line">  user: config.database.USERNAME,</div><div class="line">  password: config.database.PASSWORD,</div><div class="line">  database: config.database.DATABASE,</div><div class="line">  host: config.database.HOST,</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 配置session中间件</span></div><div class="line">app.use(session(&#123;</div><div class="line">  key: <span class="string">'USER_SID'</span>,</div><div class="line">  store: <span class="keyword">new</span> MysqlStore(sessionMysqlConfig)</div><div class="line">&#125;))</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">// 配置静态资源加载中间件</span></div><div class="line">app.use(koaStatic(</div><div class="line">  path.join(__dirname , <span class="string">'./public'</span>)</div><div class="line">))</div><div class="line"></div><div class="line"><span class="comment">// 配置服务端模板渲染引擎中间件</span></div><div class="line">app.use(views(path.join(__dirname, <span class="string">'./views'</span>), &#123;</div><div class="line">  extension: <span class="string">'ejs'</span></div><div class="line">&#125;))</div><div class="line"></div><div class="line"><span class="comment">// 使用表单解析中间件</span></div><div class="line">app.use(bodyParser())</div><div class="line"></div><div class="line"><span class="comment">// 使用新建的路由文件</span></div><div class="line"><span class="comment">// app.use(require('./routers/signin.js').routes())</span></div><div class="line">app.use(<span class="built_in">require</span>(<span class="string">'./routers/signup.js'</span>).routes())</div><div class="line"><span class="comment">// app.use(require('./routers/posts.js').routes())</span></div><div class="line"><span class="comment">// app.use(require('./routers/signout.js').routes())</span></div><div class="line"></div><div class="line"><span class="comment">// 监听在3000端口</span></div><div class="line">app.listen(<span class="number">3000</span>)</div><div class="line"></div><div class="line"><span class="built_in">console</span>.log(<span class="string">`listening on port <span class="subst">$&#123;config.port&#125;</span>`</span>)</div></pre></td></tr></table></figure>
<p>我们使用<code>koa-session-minimal``koa-mysql-session</code>来进行数据库的操作<br>使用<code>koa-static</code>配置静态资源，目录设置为<code>public</code><br>使用<code>ejs</code>模板引擎<br>使用<code>koa-bodyparser</code>来解析提交的表单信息<br>使用<code>koa-router</code>做路由</p>
<p>之前我们配置了default.js，我们就可以在这里使用了<br>首先引入进来 var config = require(‘./config/default.js’);<br>然后在数据库的操作的时候，如config.database.USERNAME，得到的就是root。</p>
<p>如果你觉得这篇文章帮助到了你，那就赏脸给个star吧，<a href="https://github.com/wclimb/Koa2-blog" target="_blank" rel="external">https://github.com/wclimb/Koa2-blog</a></p>
<h2 id="配置lib的mysql-js文件"><a href="#配置lib的mysql-js文件" class="headerlink" title="配置lib的mysql.js文件"></a>配置lib的mysql.js文件</h2><p>关于数据库的使用这里介绍一下，首先我们建立了数据库的连接池，以便后面的操作都可以使用到，我们创建了一个函数<code>query</code>，通过返回promise的方式以便可以方便用<code>.then()</code>来获取数据库返回的数据，然后我们定义了三个表的字段，通过<code>createTable</code>来创建我们后面所需的三个表，包括posts(存储文章)，users(存储用户)，comment(存储评论)，create table if not exists users()表示如果users表不存在则创建该表，避免每次重复建表报错的情况。后面我们定义了一系列的方法，最后把他们exports暴露出去。</p>
<blockquote>
<p>这里只介绍注册用户insertData，后续的可以自行查看，都差不多</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 注册用户</span></div><div class="line"><span class="keyword">let</span> insertData = <span class="function"><span class="keyword">function</span>(<span class="params"> value </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">"insert into users(name,pass) values(?,?);"</span></div><div class="line">  <span class="keyword">return</span> query( _sql, value )</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>我们写了一个_sql的sql语句，意思是插入到users的表中（在这之前我们已经建立了users表）然后要插入的数据分别是name和pass，就是用户名和密码，后面values(?,?)意思很简单，你有几个值就写几个问号，最后调用<code>query</code>函数把sql语句传进去</p>
<p>lib/mysql.js<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div><div class="line">145</div><div class="line">146</div><div class="line">147</div><div class="line">148</div><div class="line">149</div><div class="line">150</div><div class="line">151</div><div class="line">152</div><div class="line">153</div><div class="line">154</div><div class="line">155</div><div class="line">156</div><div class="line">157</div><div class="line">158</div><div class="line">159</div><div class="line">160</div><div class="line">161</div><div class="line">162</div><div class="line">163</div><div class="line">164</div><div class="line">165</div><div class="line">166</div><div class="line">167</div><div class="line">168</div><div class="line">169</div><div class="line">170</div><div class="line">171</div><div class="line">172</div><div class="line">173</div><div class="line">174</div><div class="line">175</div><div class="line">176</div><div class="line">177</div><div class="line">178</div><div class="line">179</div><div class="line">180</div><div class="line">181</div><div class="line">182</div><div class="line">183</div><div class="line">184</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> mysql = <span class="built_in">require</span>(<span class="string">'mysql'</span>);</div><div class="line"><span class="keyword">var</span> config = <span class="built_in">require</span>(<span class="string">'../config/default.js'</span>)</div><div class="line"></div><div class="line"><span class="keyword">var</span> pool  = mysql.createPool(&#123;</div><div class="line">  host     : config.database.HOST,</div><div class="line">  user     : config.database.USERNAME,</div><div class="line">  password : config.database.PASSWORD,</div><div class="line">  database : config.database.DATABASE</div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="keyword">let</span> query = <span class="function"><span class="keyword">function</span>(<span class="params"> sql, values </span>) </span>&#123;</div><div class="line"></div><div class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params"> resolve, reject </span>) =&gt;</span> &#123;</div><div class="line">    pool.getConnection(<span class="function"><span class="keyword">function</span>(<span class="params">err, connection</span>) </span>&#123;</div><div class="line">      <span class="keyword">if</span> (err) &#123;</div><div class="line">        resolve( err )</div><div class="line">      &#125; <span class="keyword">else</span> &#123;</div><div class="line">        connection.query(sql, values, ( err, rows) =&gt; &#123;</div><div class="line"></div><div class="line">          <span class="keyword">if</span> ( err ) &#123;</div><div class="line">            reject( err )</div><div class="line">          &#125; <span class="keyword">else</span> &#123;</div><div class="line">            resolve( rows )</div><div class="line">          &#125;</div><div class="line">          connection.release()</div><div class="line">        &#125;)</div><div class="line">      &#125;</div><div class="line">    &#125;)</div><div class="line">  &#125;)</div><div class="line"></div><div class="line">&#125;</div><div class="line"></div><div class="line">users=</div><div class="line"><span class="string">`create table if not exists users(</span></div><div class="line"><span class="string"> id INT NOT NULL AUTO_INCREMENT,</span></div><div class="line"><span class="string"> name VARCHAR(100) NOT NULL,</span></div><div class="line"><span class="string"> pass VARCHAR(40) NOT NULL,</span></div><div class="line"><span class="string"> PRIMARY KEY ( id )</span></div><div class="line"><span class="string">);`</span></div><div class="line"></div><div class="line">posts=</div><div class="line"><span class="string">`create table if not exists posts(</span></div><div class="line"><span class="string"> id INT NOT NULL AUTO_INCREMENT,</span></div><div class="line"><span class="string"> name VARCHAR(100) NOT NULL,</span></div><div class="line"><span class="string"> title VARCHAR(40) NOT NULL,</span></div><div class="line"><span class="string"> content  VARCHAR(40) NOT NULL,</span></div><div class="line"><span class="string"> uid  VARCHAR(40) NOT NULL,</span></div><div class="line"><span class="string"> moment  VARCHAR(40) NOT NULL,</span></div><div class="line"><span class="string"> comments  VARCHAR(40) NOT NULL DEFAULT '0',</span></div><div class="line"><span class="string"> pv  VARCHAR(40) NOT NULL DEFAULT '0',</span></div><div class="line"><span class="string"> PRIMARY KEY ( id )</span></div><div class="line"><span class="string">);`</span></div><div class="line"></div><div class="line">comment=</div><div class="line"><span class="string">`create table if not exists comment(</span></div><div class="line"><span class="string"> id INT NOT NULL AUTO_INCREMENT,</span></div><div class="line"><span class="string"> name VARCHAR(100) NOT NULL,</span></div><div class="line"><span class="string"> content VARCHAR(40) NOT NULL,</span></div><div class="line"><span class="string"> postid VARCHAR(40) NOT NULL,</span></div><div class="line"><span class="string"> PRIMARY KEY ( id )</span></div><div class="line"><span class="string">);`</span></div><div class="line"></div><div class="line"><span class="keyword">let</span> createTable = <span class="function"><span class="keyword">function</span>(<span class="params"> sql </span>) </span>&#123;</div><div class="line">  <span class="keyword">return</span> query( sql, [] )</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 建表</span></div><div class="line">createTable(users)</div><div class="line">createTable(posts)</div><div class="line">createTable(comment)</div><div class="line"></div><div class="line"><span class="comment">// 注册用户</span></div><div class="line"><span class="keyword">let</span> insertData = <span class="function"><span class="keyword">function</span>(<span class="params"> value </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">"insert into users(name,pass) values(?,?);"</span></div><div class="line">  <span class="keyword">return</span> query( _sql, value )</div><div class="line">&#125;</div><div class="line"><span class="comment">// 发表文章</span></div><div class="line"><span class="keyword">let</span> insertPost = <span class="function"><span class="keyword">function</span>(<span class="params"> value </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">"insert into posts(name,title,content,uid,moment) values(?,?,?,?,?);"</span></div><div class="line">  <span class="keyword">return</span> query( _sql, value )</div><div class="line">&#125;</div><div class="line"><span class="comment">// 更新文章评论数</span></div><div class="line"><span class="keyword">let</span> updatePostComment = <span class="function"><span class="keyword">function</span>(<span class="params"> value </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">"update posts set  comments=? where id=?"</span></div><div class="line">  <span class="keyword">return</span> query( _sql, value )</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 更新浏览数</span></div><div class="line"><span class="keyword">let</span> updatePostPv = <span class="function"><span class="keyword">function</span>(<span class="params"> value </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">"update posts set  pv=? where id=?"</span></div><div class="line">  <span class="keyword">return</span> query( _sql, value )</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 发表评论</span></div><div class="line"><span class="keyword">let</span> insertComment = <span class="function"><span class="keyword">function</span>(<span class="params"> value </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">"insert into comment(name,content,postid) values(?,?,?);"</span></div><div class="line">  <span class="keyword">return</span> query( _sql, value )</div><div class="line">&#125;</div><div class="line"><span class="comment">// 通过名字查找用户</span></div><div class="line"><span class="keyword">let</span> findDataByName = <span class="function"><span class="keyword">function</span> (<span class="params">  name </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">`</span></div><div class="line"><span class="string">    SELECT * from users</span></div><div class="line"><span class="string">      where name="<span class="subst">$&#123;name&#125;</span>"</span></div><div class="line"><span class="string">      `</span></div><div class="line">  <span class="keyword">return</span> query( _sql)</div><div class="line">&#125;</div><div class="line"><span class="comment">// 通过文章的名字查找用户</span></div><div class="line"><span class="keyword">let</span> findDataByUser = <span class="function"><span class="keyword">function</span> (<span class="params">  name </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">`</span></div><div class="line"><span class="string">    SELECT * from posts</span></div><div class="line"><span class="string">      where name="<span class="subst">$&#123;name&#125;</span>"</span></div><div class="line"><span class="string">      `</span></div><div class="line">  <span class="keyword">return</span> query( _sql)</div><div class="line">&#125;</div><div class="line"><span class="comment">// 通过文章id查找</span></div><div class="line"><span class="keyword">let</span> findDataById = <span class="function"><span class="keyword">function</span> (<span class="params">  id </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">`</span></div><div class="line"><span class="string">    SELECT * from posts</span></div><div class="line"><span class="string">      where id="<span class="subst">$&#123;id&#125;</span>"</span></div><div class="line"><span class="string">      `</span></div><div class="line">  <span class="keyword">return</span> query( _sql)</div><div class="line">&#125;</div><div class="line"><span class="comment">// 通过评论id查找</span></div><div class="line"><span class="keyword">let</span> findCommentById = <span class="function"><span class="keyword">function</span> (<span class="params"> id </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">`</span></div><div class="line"><span class="string">    SELECT * FROM comment where postid="<span class="subst">$&#123;id&#125;</span>"</span></div><div class="line"><span class="string">      `</span></div><div class="line">  <span class="keyword">return</span> query( _sql)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 查询所有文章</span></div><div class="line"><span class="keyword">let</span> findAllPost = <span class="function"><span class="keyword">function</span> (<span class="params">  </span>) </span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql = <span class="string">`</span></div><div class="line"><span class="string">    SELECT * FROM posts</span></div><div class="line"><span class="string">      `</span></div><div class="line">  <span class="keyword">return</span> query( _sql)</div><div class="line">&#125;</div><div class="line"><span class="comment">// 更新修改文章</span></div><div class="line"><span class="keyword">let</span> updatePost = <span class="function"><span class="keyword">function</span>(<span class="params">values</span>)</span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql=<span class="string">`update posts set  title=?,content=? where id=?`</span></div><div class="line">  <span class="keyword">return</span> query(_sql,values)</div><div class="line">&#125;</div><div class="line"><span class="comment">// 删除文章</span></div><div class="line"><span class="keyword">let</span> deletePost = <span class="function"><span class="keyword">function</span>(<span class="params">id</span>)</span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql=<span class="string">`delete from posts where id = <span class="subst">$&#123;id&#125;</span>`</span></div><div class="line">  <span class="keyword">return</span> query(_sql)</div><div class="line">&#125;</div><div class="line"><span class="comment">// 删除评论</span></div><div class="line"><span class="keyword">let</span> deleteComment = <span class="function"><span class="keyword">function</span>(<span class="params">id</span>)</span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql=<span class="string">`delete from comment where id = <span class="subst">$&#123;id&#125;</span>`</span></div><div class="line">  <span class="keyword">return</span> query(_sql)</div><div class="line">&#125;</div><div class="line"><span class="comment">// 删除所有评论</span></div><div class="line"><span class="keyword">let</span> deleteAllPostComment = <span class="function"><span class="keyword">function</span>(<span class="params">id</span>)</span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql=<span class="string">`delete from comment where postid = <span class="subst">$&#123;id&#125;</span>`</span></div><div class="line">  <span class="keyword">return</span> query(_sql)</div><div class="line">&#125;</div><div class="line"><span class="comment">// 查找</span></div><div class="line"><span class="keyword">let</span> findCommentLength = <span class="function"><span class="keyword">function</span>(<span class="params">id</span>)</span>&#123;</div><div class="line">  <span class="keyword">let</span> _sql=<span class="string">`select content from comment where postid in (select id from posts where id=<span class="subst">$&#123;id&#125;</span>)`</span></div><div class="line">  <span class="keyword">return</span> query(_sql)</div><div class="line">&#125;</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"><span class="built_in">module</span>.exports=&#123;</div><div class="line">  query,</div><div class="line">  createTable,</div><div class="line">  insertData,</div><div class="line">  findDataByName,</div><div class="line">  insertPost,</div><div class="line">  findAllPost,</div><div class="line">  findDataByUser,</div><div class="line">  findDataById,</div><div class="line">  insertComment,</div><div class="line">  findCommentById,</div><div class="line">  updatePost,</div><div class="line">  deletePost,</div><div class="line">  deleteComment,</div><div class="line">  findCommentLength,</div><div class="line">  updatePostComment,</div><div class="line">  deleteAllPostComment,</div><div class="line">  updatePostPv</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>下面是我们建的表</p>
<table>
<thead>
<tr>
<th style="text-align:center">users</th>
<th style="text-align:center">posts</th>
<th style="text-align:center">comment</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">id</td>
<td style="text-align:center">id</td>
<td style="text-align:center">id</td>
</tr>
<tr>
<td style="text-align:center">name</td>
<td style="text-align:center">name</td>
<td style="text-align:center">name</td>
</tr>
<tr>
<td style="text-align:center">pass</td>
<td style="text-align:center">title</td>
<td style="text-align:center">content</td>
</tr>
<tr>
<td style="text-align:center"></td>
<td style="text-align:center">content</td>
<td style="text-align:center">postid</td>
</tr>
<tr>
<td style="text-align:center"></td>
<td style="text-align:center">uid</td>
<td style="text-align:center"></td>
</tr>
<tr>
<td style="text-align:center"></td>
<td style="text-align:center">moment</td>
<td style="text-align:center"></td>
</tr>
<tr>
<td style="text-align:center"></td>
<td style="text-align:center">comments</td>
<td style="text-align:center"></td>
</tr>
<tr>
<td style="text-align:center"></td>
<td style="text-align:center">pv</td>
<td style="text-align:center"></td>
</tr>
</tbody>
</table>
<ul>
<li>id主键递增</li>
<li>name: 用户名</li>
<li>pass：密码</li>
<li>title：文章标题</li>
<li>content：文章内容和评论</li>
<li>uid：发表文章的用户id </li>
<li>moment：创建时间</li>
<li>comments：文章评论数</li>
<li>pv：文章浏览数</li>
<li>postid：文章id</li>
</ul>
<p>现在感觉有点枯燥，那我们先来实现一下注册吧</p>
<h2 id="实现注册页面"><a href="#实现注册页面" class="headerlink" title="实现注册页面"></a>实现注册页面</h2><p>routers/singup.js </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> router=<span class="built_in">require</span>(<span class="string">'koa-router'</span>)();</div><div class="line"></div><div class="line"><span class="comment">// GET '/signup' 注册页</span></div><div class="line"></div><div class="line">router.get(<span class="string">'/signup'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line"> <span class="keyword">await</span> ctx.render(<span class="string">'signup'</span>,&#123;		</div><div class="line"> &#125;)</div><div class="line">&#125;)</div><div class="line"></div><div class="line"><span class="built_in">module</span>.exports=router</div></pre></td></tr></table></figure>
<p>使用get方式得到’/signup’页面，然后渲染signup模板，这里我们还没有在写signup.ejs</p>
<p>views/signup.ejs</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"container"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"form create"</span> <span class="attr">method</span>=<span class="string">"post"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>用户名：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">placeholder</span>=<span class="string">"用户名"</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"name"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>密码：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">"password"</span> <span class="attr">type</span>=<span class="string">"password"</span> <span class="attr">name</span>=<span class="string">"password"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>重复密码：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">"repeatpass"</span> <span class="attr">type</span>=<span class="string">"password"</span> <span class="attr">name</span>=<span class="string">"repeatpass"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"submit"</span>&gt;</span>注册<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">form</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></div></pre></td></tr></table></figure>
<p>我们先安装supervisor</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ cnpm i supervisor</div></pre></td></tr></table></figure>
<p>supervisor的作用是会监听文件的变化，而我们修改文件之后不必去重启程序<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">supervisor --harmony index</div></pre></td></tr></table></figure></p>
<p>现在访问 localhost:3000/signup 看看效果吧。注意数据库一定要是开启的状态，不能关闭</p>
<h2 id="完善注册功能"><a href="#完善注册功能" class="headerlink" title="完善注册功能"></a>完善注册功能</h2><p>首先我们来完善一下样式吧，稍微美化一下</p>
<p>public/index.css</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div><div class="line">145</div><div class="line">146</div><div class="line">147</div><div class="line">148</div><div class="line">149</div><div class="line">150</div><div class="line">151</div><div class="line">152</div><div class="line">153</div><div class="line">154</div><div class="line">155</div><div class="line">156</div><div class="line">157</div><div class="line">158</div><div class="line">159</div><div class="line">160</div><div class="line">161</div><div class="line">162</div><div class="line">163</div><div class="line">164</div><div class="line">165</div><div class="line">166</div><div class="line">167</div><div class="line">168</div><div class="line">169</div><div class="line">170</div><div class="line">171</div><div class="line">172</div><div class="line">173</div></pre></td><td class="code"><pre><div class="line"><span class="selector-tag">body</span>,<span class="selector-tag">header</span>,<span class="selector-tag">ul</span>,<span class="selector-tag">li</span>,<span class="selector-tag">p</span>,<span class="selector-tag">div</span>,<span class="selector-tag">html</span>,<span class="selector-tag">span</span>,<span class="selector-tag">h3</span>,<span class="selector-tag">a</span>&#123;</div><div class="line">	<span class="attribute">margin</span>: <span class="number">0</span>;</div><div class="line">	<span class="attribute">padding</span>: <span class="number">0</span>;</div><div class="line">	<span class="attribute">color</span>: <span class="number">#333</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-tag">body</span>&#123;</div><div class="line">	<span class="attribute">margin-bottom</span>: <span class="number">20px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-tag">a</span>&#123;</div><div class="line">	<span class="attribute">text-decoration</span>: none;</div><div class="line">&#125;</div><div class="line"><span class="selector-tag">header</span>&#123;</div><div class="line">	<span class="attribute">width</span>: <span class="number">60%</span>;</div><div class="line">	<span class="attribute">margin</span>: <span class="number">20px</span> auto;</div><div class="line">	<span class="attribute">display</span>: -webkit-flex;</div><div class="line">	<span class="attribute">display</span>: -moz-flex;</div><div class="line">	<span class="attribute">display</span>: -ms-flex;</div><div class="line">	<span class="attribute">display</span>: -o-flex;</div><div class="line">	<span class="attribute">display</span>: flex;</div><div class="line">	<span class="attribute">justify-content</span>: space-between;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.user_name</span>&#123;</div><div class="line">	<span class="attribute">font-size</span>: <span class="number">20px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.has_user</span>&#123;</div><div class="line">	</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.has_user</span> <span class="selector-tag">a</span>,<span class="selector-class">.has_user</span> <span class="selector-tag">span</span>,<span class="selector-class">.none_user</span> <span class="selector-tag">a</span>&#123;</div><div class="line">	<span class="attribute">padding</span>: <span class="number">5px</span> <span class="number">15px</span>;</div><div class="line">	<span class="attribute">background</span>: <span class="number">#5FB878</span>;</div><div class="line">	<span class="attribute">border-radius</span>: <span class="number">15px</span>;</div><div class="line">	<span class="attribute">color</span>: <span class="number">#fff</span>;</div><div class="line">	<span class="attribute">cursor</span>: pointer;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.posts</span>&#123;</div><div class="line">	<span class="attribute">list-style</span>: none;</div><div class="line">	<span class="attribute">width</span>: <span class="number">60%</span>;</div><div class="line">	<span class="attribute">margin</span>: <span class="number">0</span> auto;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.posts</span> <span class="selector-tag">li</span>&#123;</div><div class="line">	<span class="attribute">margin-top</span>: <span class="number">10px</span>;</div><div class="line">	<span class="attribute">border</span>: <span class="number">1px</span> solid <span class="number">#ccc</span>;</div><div class="line">	<span class="attribute">border-radius</span>: <span class="number">5px</span>;</div><div class="line">	<span class="attribute">position</span>: relative;</div><div class="line">	<span class="attribute">padding-bottom</span>: <span class="number">50px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-tag">h3</span>&#123;</div><div class="line">	<span class="attribute">display</span>: inline-block;</div><div class="line">	<span class="attribute">padding</span>: <span class="number">5px</span> <span class="number">10px</span>;</div><div class="line">	<span class="attribute">background</span>: <span class="number">#1E9FFF</span>;</div><div class="line">	<span class="attribute">color</span>: <span class="number">#fff</span>;</div><div class="line">	<span class="attribute">border-radius</span>: <span class="number">10px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.post_title</span> <span class="selector-tag">p</span>,<span class="selector-class">.post_content</span> <span class="selector-tag">p</span>&#123;</div><div class="line">	<span class="attribute">margin</span>: <span class="number">10px</span> <span class="number">0</span>;</div><div class="line">	<span class="attribute">background</span>: <span class="number">#eee</span>;</div><div class="line">	<span class="attribute">padding</span>: <span class="number">10px</span> <span class="number">20px</span>;</div><div class="line">	<span class="attribute">border</span>: <span class="number">1px</span> solid <span class="number">#ddd</span>;</div><div class="line">	<span class="attribute">border-radius</span>: <span class="number">4px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.post_time</span>&#123;</div><div class="line">	<span class="attribute">position</span>: absolute;</div><div class="line">	<span class="attribute">bottom</span>: <span class="number">5px</span>;</div><div class="line">	<span class="attribute">right</span>: <span class="number">10px</span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="selector-class">.post_3</span>&#123;</div><div class="line">	<span class="attribute">position</span>: absolute;</div><div class="line">	<span class="attribute">bottom</span>: <span class="number">5px</span>;</div><div class="line">	<span class="attribute">left</span>: <span class="number">10px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.post_3</span> <span class="selector-tag">p</span>&#123;</div><div class="line">	<span class="attribute">display</span>: inline-block;</div><div class="line">	<span class="attribute">margin-left</span>: <span class="number">5px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.post_title</span>&#123;</div><div class="line">	<span class="attribute">padding</span>: <span class="number">10px</span> <span class="number">20px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.post_content</span>&#123;</div><div class="line">	<span class="attribute">padding</span>: <span class="number">0</span> <span class="number">20px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.spost</span>&#123;</div><div class="line">	<span class="attribute">width</span>: <span class="number">60%</span>;</div><div class="line">	<span class="attribute">margin</span>:<span class="number">0</span> auto;</div><div class="line">	<span class="attribute">border</span>: <span class="number">1px</span> solid <span class="number">#ddd</span>;</div><div class="line">	<span class="attribute">position</span>: relative;</div><div class="line">	<span class="attribute">padding-bottom</span>: <span class="number">40px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.spost_user</span>&#123;</div><div class="line">	<span class="attribute">position</span>: absolute;</div><div class="line">	<span class="attribute">left</span>: <span class="number">20px</span>;</div><div class="line">	<span class="attribute">bottom</span>: <span class="number">5px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.edit</span>&#123;</div><div class="line">	<span class="attribute">position</span>: absolute;</div><div class="line">	<span class="attribute">right</span>: <span class="number">20px</span>;</div><div class="line">	<span class="attribute">bottom</span>: <span class="number">5px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.edit</span> <span class="selector-tag">p</span>&#123;</div><div class="line">	<span class="attribute">display</span>: inline-block;</div><div class="line">	<span class="attribute">margin-left</span>: <span class="number">10px</span>;	</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.comment_wrap</span>&#123;</div><div class="line">	<span class="attribute">width</span>: <span class="number">60%</span>;</div><div class="line">	<span class="attribute">margin</span>:<span class="number">20px</span> auto;	</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.submit</span>&#123;</div><div class="line">	<span class="attribute">display</span>: block;</div><div class="line">	<span class="attribute">width</span>: <span class="number">90px</span>;</div><div class="line">	<span class="attribute">height</span>: <span class="number">35px</span>;</div><div class="line">	<span class="attribute">line-height</span>: <span class="number">35px</span>;</div><div class="line">	<span class="attribute">text-align</span>: center;</div><div class="line">	<span class="attribute">border-radius</span>: <span class="number">10px</span>;</div><div class="line">	<span class="attribute">background</span>: <span class="number">#5FB878</span>;</div><div class="line">	<span class="attribute">cursor</span>: pointer;</div><div class="line">	<span class="attribute">color</span>: <span class="number">#fff</span>;</div><div class="line">	<span class="attribute">float</span>: right;</div><div class="line">	<span class="attribute">margin-top</span>: <span class="number">20px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.cmt_content</span>&#123;</div><div class="line">	<span class="attribute">background</span>: <span class="number">#eee</span>;</div><div class="line">	<span class="attribute">padding</span>: <span class="number">20px</span> ;</div><div class="line">	<span class="attribute">position</span>: relative;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.cmt_name</span>&#123;</div><div class="line">	<span class="attribute">position</span>: absolute;</div><div class="line">	<span class="attribute">right</span>: <span class="number">20px</span>;</div><div class="line">	<span class="attribute">bottom</span>: <span class="number">5px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.cmt_name</span> <span class="selector-tag">a</span>&#123;</div><div class="line">	<span class="attribute">margin-left</span>: <span class="number">10px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.cmt_content</span>&#123;</div><div class="line">	<span class="attribute">margin-top</span>: <span class="number">10px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.form</span>&#123;</div><div class="line">	<span class="attribute">margin</span>:<span class="number">0</span> auto;</div><div class="line">	<span class="attribute">width</span>: <span class="number">50%</span>;</div><div class="line">	<span class="attribute">margin-top</span>: <span class="number">20px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-tag">textarea</span>&#123;</div><div class="line">	<span class="attribute">width</span>: <span class="number">100%</span>;</div><div class="line">	<span class="attribute">height</span>: <span class="number">200px</span>;</div><div class="line">	<span class="attribute">padding-left</span>: <span class="number">20px</span>;</div><div class="line">	<span class="attribute">font-size</span>: <span class="number">20px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.container</span>&#123;</div><div class="line">	<span class="attribute">width</span>: <span class="number">60%</span>;</div><div class="line">	<span class="attribute">margin</span>: <span class="number">0</span> auto;</div><div class="line">&#125;</div><div class="line"><span class="selector-tag">input</span>&#123;</div><div class="line">	<span class="attribute">display</span>: block;</div><div class="line">	<span class="attribute">width</span>: <span class="number">100%</span>;</div><div class="line">	<span class="attribute">height</span>: <span class="number">40px</span>;</div><div class="line">	<span class="attribute">padding-left</span>: <span class="number">20px</span>;</div><div class="line">	<span class="attribute">font-size</span>: <span class="number">20px</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.create</span> <span class="selector-tag">label</span>&#123;</div><div class="line">	<span class="attribute">display</span>: block;</div><div class="line">	<span class="attribute">margin</span>: <span class="number">10px</span> <span class="number">0</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.comment_wrap</span> <span class="selector-tag">form</span>&#123;</div><div class="line">	<span class="attribute">width</span>: <span class="number">100%</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.delete_comment</span>,<span class="selector-class">.delete_post</span>&#123;</div><div class="line">	<span class="attribute">cursor</span>: pointer;</div><div class="line">&#125;</div><div class="line"><span class="selector-class">.delete_comment</span><span class="selector-pseudo">:hover</span>,<span class="selector-class">.delete_post</span><span class="selector-pseudo">:hover</span>&#123;</div><div class="line">	<span class="attribute">color</span>: <span class="number">#f60</span>;</div><div class="line">&#125;</div><div class="line"><span class="selector-tag">a</span><span class="selector-pseudo">:hover</span>&#123;</div><div class="line">	<span class="attribute">color</span>: <span class="number">#f60</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>我们再把模板引擎的header和footer独立出来</p>
<p>/views/header.ejs<br>顺便引入index.css和jq<br><figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"stylesheet"</span> <span class="attr">href</span>=<span class="string">"/index.css"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></div></pre></td></tr></table></figure></p>
<p>/views/footer.ejs</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">	</div><div class="line">&lt;/body&gt;</div><div class="line">&lt;/html&gt;</div></pre></td></tr></table></figure>
<p>修改views/signup.ejs </p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">header</span> %&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"container"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"form create"</span> <span class="attr">method</span>=<span class="string">"post"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>用户名：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">placeholder</span>=<span class="string">"用户名"</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"name"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>密码：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">"password"</span> <span class="attr">type</span>=<span class="string">"password"</span> <span class="attr">name</span>=<span class="string">"password"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>重复密码：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">"repeatpass"</span> <span class="attr">type</span>=<span class="string">"password"</span> <span class="attr">name</span>=<span class="string">"repeatpass"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"submit"</span>&gt;</span>注册<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">form</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">footer</span> %&gt;</span></div></pre></td></tr></table></figure>
<p>修改routers/signup.js</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> router=<span class="built_in">require</span>(<span class="string">'koa-router'</span>)();</div><div class="line"><span class="comment">// 处理数据库（之前已经写好，在mysql.js）</span></div><div class="line"><span class="keyword">var</span> userModel=<span class="built_in">require</span>(<span class="string">'../lib/mysql.js'</span>);</div><div class="line"><span class="comment">// 加密</span></div><div class="line"><span class="keyword">var</span> md5=<span class="built_in">require</span>(<span class="string">'md5'</span>)</div><div class="line"></div><div class="line">router.get(<span class="string">'/signup'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="keyword">await</span> ctx.render(<span class="string">'signup'</span>,&#123;</div><div class="line">		session:ctx.session,</div><div class="line">	&#125;)</div><div class="line">&#125;)</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment">// POST '/signup' 注册页</span></div><div class="line">router.post(<span class="string">'/signup'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="built_in">console</span>.log(ctx.request.body)</div><div class="line">	<span class="keyword">var</span> user=&#123;</div><div class="line">		name:ctx.request.body.name,</div><div class="line">		pass:ctx.request.body.password,</div><div class="line">		repeatpass:ctx.request.body.repeatpass</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">await</span> userModel.findDataByName(user.name)</div><div class="line">			.then(<span class="function"><span class="params">result</span>=&gt;</span>&#123;</div><div class="line">				<span class="comment">// var res=JSON.parse(JSON.stringify(reslut))</span></div><div class="line">				<span class="built_in">console</span>.log(result)</div><div class="line"></div><div class="line">				<span class="keyword">if</span> (result.length)&#123;</div><div class="line">					<span class="keyword">try</span> &#123;</div><div class="line">						<span class="keyword">throw</span> <span class="built_in">Error</span>(<span class="string">'用户存在'</span>)</div><div class="line">					&#125;<span class="keyword">catch</span> (error)&#123;</div><div class="line">						<span class="comment">//处理err</span></div><div class="line">						<span class="built_in">console</span>.log(error)	</div><div class="line">					&#125;			</div><div class="line">					ctx.body=&#123;</div><div class="line">						data:<span class="number">1</span></div><div class="line">					&#125;;;				</div><div class="line">				&#125;<span class="keyword">else</span> <span class="keyword">if</span> (user.pass!==user.repeatpass || user.pass==<span class="string">''</span>)&#123;</div><div class="line">					ctx.body=&#123;</div><div class="line">						data:<span class="number">2</span></div><div class="line">					&#125;;				</div><div class="line">				&#125;<span class="keyword">else</span>&#123;</div><div class="line">					ctx.body=&#123;</div><div class="line">						data:<span class="number">3</span></div><div class="line">					&#125;;</div><div class="line">					<span class="built_in">console</span>.log(<span class="string">'注册成功'</span>)</div><div class="line">					<span class="comment">// ctx.session.user=ctx.request.body.name</span></div><div class="line">			 		userModel.insertData([ctx.request.body.name,md5(ctx.request.body.password)])</div><div class="line">				&#125;							</div><div class="line">			&#125;)</div><div class="line"></div><div class="line">&#125;)</div><div class="line"></div><div class="line"></div><div class="line"><span class="built_in">module</span>.exports=router</div></pre></td></tr></table></figure>
<ul>
<li>我们使用md5实现密码加密</li>
<li>使用我们之前说的<code>bodyParse</code>来解析提交的数据，通过<code>ctx.request.body</code>得到</li>
<li>我们引入了数据库的操作 findDataByName和insertData，因为之前我们在/lib/mysql.js中已经把他们写好，并暴露出来了。意思是先从数据库里面查找注册的用户名，如果找到了证明该用户名已经被注册过了，如果没有找到则使用insertData增加到数据库中</li>
<li>ctx.body 是我们通过ajax提交之后给页面返回的数据，比如提交ajax成功之后<code>msg.data=1</code>的时候就代表用户存在，<code>msg.data</code>出现在后面的<code>signup.ejs</code>模板ajax请求中</li>
</ul>
<p>我们使用ajax来提交数据，方便来做成功错误的处理</p>
<h2 id="模板引擎ejs"><a href="#模板引擎ejs" class="headerlink" title="模板引擎ejs"></a>模板引擎ejs</h2><p>我们使用的是ejs，语法可以见<a href="https://www.npmjs.com/package/ejs" target="_blank" rel="external">ejs官网</a></p>
<p>之前我们写了这么一段代码<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">router.get(<span class="string">'/signup'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="keyword">await</span> ctx.render(<span class="string">'signup'</span>,&#123;</div><div class="line">		session:ctx.session,</div><div class="line">	&#125;)</div><div class="line">&#125;)</div></pre></td></tr></table></figure></p>
<p>这里就用到了ejs所需的session 我们通过渲染signup.ejs模板，将值ctx.session赋值给session，之后我们就可以在signup.ejs中使用了<br>ejs的常用标签为：</p>
<ul>
<li><code>&lt;% code %&gt;</code>：运行 JavaScript 代码，不输出</li>
<li><code>&lt;%= code %&gt;</code>：显示转义后的 HTML内容</li>
<li><code>&lt;%- code %&gt;</code>：显示原始 HTML 内容</li>
</ul>
<p><code>&lt;%= code %&gt;</code>和<code>&lt;%- code %&gt;</code>的区别在于，&lt;%= code %&gt;不管你写什么都会原样输出，比如code为 <code>&lt;strong&gt;hello&lt;/strong&gt;</code>的时候 <code>&lt;%= code %&gt;</code> 会显示<code>&lt;strong&gt;hello&lt;/strong&gt;</code><br>而<code>&lt;%- code %&gt;</code>则显示加粗的hello</p>
<p>修改/views/signup.ejs</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">header</span> %&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"container"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"form create"</span> <span class="attr">method</span>=<span class="string">"post"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>用户名：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">placeholder</span>=<span class="string">"用户名"</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"name"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>密码：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">"password"</span> <span class="attr">type</span>=<span class="string">"password"</span> <span class="attr">name</span>=<span class="string">"password"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>重复密码：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">class</span>=<span class="string">"repeatpass"</span> <span class="attr">type</span>=<span class="string">"password"</span> <span class="attr">name</span>=<span class="string">"repeatpass"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"submit"</span>&gt;</span>注册<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">form</span>&gt;</span>	</div><div class="line">	<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></div><div class="line"><span class="javascript">		$(<span class="string">'.submit'</span>).click(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">			<span class="built_in">console</span>.log($(<span class="string">'.form'</span>).serialize())</span></div><div class="line"><span class="javascript">			$.ajax(&#123;</span></div><div class="line"><span class="javascript">	            url: <span class="string">"/signup"</span>,</span></div><div class="line"><span class="javascript">	            data: $(<span class="string">'.form'</span>).serialize(),</span></div><div class="line"><span class="javascript">	            type: <span class="string">"POST"</span>,</span></div><div class="line"><span class="javascript">	            cache: <span class="literal">false</span>,</span></div><div class="line"><span class="javascript">	            dataType: <span class="string">'json'</span>,</span></div><div class="line"><span class="javascript">	            success: <span class="function"><span class="keyword">function</span> (<span class="params">msg</span>) </span>&#123;</span></div><div class="line"><span class="javascript">	               <span class="keyword">if</span> (msg.data == <span class="number">1</span>) &#123;</span></div><div class="line"><span class="undefined">	               		</span></div><div class="line"><span class="javascript">	               		$(<span class="string">'.error'</span>).text(<span class="string">'用户名存在'</span>)</span></div><div class="line"><span class="javascript">	               		$(<span class="string">'input'</span>).val(<span class="string">''</span>)</span></div><div class="line"><span class="javascript">	               		fade(<span class="string">'.error'</span>)</span></div><div class="line"><span class="undefined">	               &#125;</span></div><div class="line"><span class="javascript">	               <span class="keyword">else</span> <span class="keyword">if</span> (msg.data == <span class="number">2</span>)&#123;</span></div><div class="line"><span class="javascript">	               		$(<span class="string">'.error'</span>).text(<span class="string">'请输入重复的密码'</span>)</span></div><div class="line"><span class="javascript">	               		fade(<span class="string">'.error'</span>)</span></div><div class="line"><span class="undefined">	               		</span></div><div class="line"><span class="undefined">	               &#125;</span></div><div class="line"><span class="javascript">	               <span class="keyword">else</span> <span class="keyword">if</span>(msg.data == <span class="number">3</span>)&#123;</span></div><div class="line"><span class="javascript">	               		$(<span class="string">'.success'</span>).text(<span class="string">'注册成功'</span>)</span></div><div class="line"><span class="javascript">	               		fade(<span class="string">'.success'</span>)</span></div><div class="line"><span class="javascript">	               		setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">	               			<span class="built_in">window</span>.location.href=<span class="string">"/signin"</span></span></div><div class="line"><span class="undefined">		  </span></div><div class="line"><span class="undefined">	               		&#125;,1000)</span></div><div class="line"><span class="undefined">	               &#125;	              </span></div><div class="line"><span class="javascript">	                <span class="comment">//console.log($('.ui.error.message').text);</span></span></div><div class="line"><span class="undefined">	            &#125;,</span></div><div class="line"><span class="javascript">	            error: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></div><div class="line"><span class="javascript">	                alert(<span class="string">'异常'</span>);</span></div><div class="line"><span class="undefined">	            &#125;</span></div><div class="line"><span class="undefined">	        &#125;)		</span></div><div class="line"><span class="undefined">		&#125;)</span></div><div class="line"><span class="undefined">	</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">footer</span> %&gt;</span></div></pre></td></tr></table></figure>
<p>这里重点就在于ajax提交了，提交之后换回数据 1 2 3，然后分别做正确错误处理，把信息写在error和success中</p>
<p>修改/views/header.ejs</p>
<blockquote>
<p> 我们之前在/routers/signup.js get ‘/signup’ 中 向模板传递了session参数  session:ctx.session,存取的就是用户的信息，包括用户名、登录之后的id等，之所以可以通过ctx.session获取到，因为我们在后面登录的时候已经赋值 如ctx.session.user=res[0][‘name’]</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">title</span>&gt;</span>koa-blog<span class="tag">&lt;/<span class="name">title</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"stylesheet"</span> <span class="attr">href</span>=<span class="string">"/index.css"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">header</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"user_name"</span>&gt;</span></div><div class="line">			user：</div><div class="line">			<span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(<span class="attr">session.user</span>)&#123; %&gt;</span></div><div class="line">				 <span class="tag">&lt;<span class="name">%=</span> <span class="attr">session.user</span> %&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(!<span class="attr">session.user</span>)&#123; %&gt;</span></div><div class="line">				未登录</div><div class="line">			<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"message"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"error"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"success"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"user_right"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span>  <span class="attr">if</span>(<span class="attr">session.user</span>)&#123; %&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"has_user"</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/posts"</span>&gt;</span>全部文章<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/create"</span>&gt;</span>发表文章<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">span</span> <span class="attr">class</span>=<span class="string">"signout"</span>&gt;</span>登出<span class="tag">&lt;/<span class="name">span</span>&gt;</span></div><div class="line">				<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(!<span class="attr">session.user</span>)&#123; %&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"none_user"</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/posts"</span>&gt;</span>全部文章<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">a</span>  <span class="attr">href</span>=<span class="string">"/signup"</span>&gt;</span>注册<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/signin"</span>&gt;</span>登录<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">				<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">header</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></div><div class="line"><span class="javascript">		<span class="function"><span class="keyword">function</span> <span class="title">fade</span>(<span class="params">data</span>)</span>&#123;</span></div><div class="line"><span class="javascript">			<span class="keyword">if</span> ($(data).css(<span class="string">'display'</span>)!==<span class="string">'none'</span>) &#123;</span></div><div class="line"><span class="javascript">           		$(data).fadeOut(<span class="number">1500</span>)</span></div><div class="line"><span class="undefined">       		&#125;</span></div><div class="line"><span class="javascript">       		<span class="keyword">else</span>&#123;</span></div><div class="line"><span class="javascript">       			$(data).show()</span></div><div class="line"><span class="javascript">           		$(data).fadeOut(<span class="number">1500</span>)</span></div><div class="line"><span class="undefined">       		&#125;</span></div><div class="line"><span class="undefined">		&#125;</span></div><div class="line"><span class="undefined">	</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div></pre></td></tr></table></figure>
<p>我们可以看到，如果不存在用户，则只显示<code>全部文章</code> <code>注册</code> <code>登录</code> ,如果session.user存在则有登出的按钮</p>
<p>我们可以看到当状态data为 3 的时候window.location.href=”/signin”<br>为了方便跳转，我们先简单实现一下signin页面</p>
<p>修改 /routers/signin.js</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> router=<span class="built_in">require</span>(<span class="string">'koa-router'</span>)();</div><div class="line"></div><div class="line"><span class="comment">// get '/signin'登录页面</span></div><div class="line">router.get(<span class="string">'/signin'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="keyword">await</span> ctx.render(<span class="string">'signin'</span>,&#123;</div><div class="line">		session:ctx.session,</div><div class="line">	&#125;)</div><div class="line">&#125;)</div><div class="line"><span class="built_in">module</span>.exports=router</div></pre></td></tr></table></figure>
<p>修改 /views/signin.ejs</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">header</span> %&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"container"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"form create"</span> <span class="attr">method</span>=<span class="string">"post "</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>用户名：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">placeholder</span>=<span class="string">"用户名"</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"name"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>密码：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">placeholder</span>=<span class="string">"密码"</span> <span class="attr">type</span>=<span class="string">"password"</span> <span class="attr">name</span>=<span class="string">"password"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"submit"</span>&gt;</span>登录<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">form</span>&gt;</span>	</div><div class="line">	<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">footer</span> %&gt;</span></div></pre></td></tr></table></figure>
<p>修改 index.js 文件 把下面这段代码注释去掉，之前注释是因为我们没有写signin的路由，以免报错，后面还有文章页和登出页的路由，大家记住一下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">app.use(<span class="built_in">require</span>(<span class="string">'./routers/signin.js'</span>).routes())</div></pre></td></tr></table></figure>
<p>现在注册一下来看看效果吧<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ supervisor --harmony index</div></pre></td></tr></table></figure></p>
<p><img src="/img/signup.png" alt="img"></p>
<p>我们怎么查看我们注册好的账号和密码呢？打开mysql控制台</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">$ select * from users;</div></pre></td></tr></table></figure>
<p>这样刚刚我们注册的用户信息都出现了<br><img src="/img/users.png" alt="img"></p>
<p>如果你觉得这篇文章帮助到了你，那就赏脸给个star吧，<a href="https://github.com/wclimb/Koa2-blog" target="_blank" rel="external">https://github.com/wclimb/Koa2-blog</a></p>
<h2 id="登录页面"><a href="#登录页面" class="headerlink" title="登录页面"></a>登录页面</h2><p>修改signin<br>routers/signin.js</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> router=<span class="built_in">require</span>(<span class="string">'koa-router'</span>)();</div><div class="line"><span class="comment">// 处理数据库（之前已经写好，在mysql.js）</span></div><div class="line"><span class="keyword">var</span> userModel=<span class="built_in">require</span>(<span class="string">'../lib/mysql.js'</span>)</div><div class="line"><span class="comment">// 加密</span></div><div class="line"><span class="keyword">var</span> md5=<span class="built_in">require</span>(<span class="string">'md5'</span>)</div><div class="line"></div><div class="line"><span class="comment">// get '/signin'登录页面</span></div><div class="line">router.get(<span class="string">'/signin'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="keyword">await</span> ctx.render(<span class="string">'signin'</span>,&#123;</div><div class="line">		session:ctx.session,</div><div class="line">	&#125;)</div><div class="line">&#125;)</div><div class="line"><span class="comment">// post '/signin'登录页面</span></div><div class="line">router.post(<span class="string">'/signin'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="built_in">console</span>.log(ctx.request.body)</div><div class="line">	<span class="keyword">var</span> name=ctx.request.body.name;</div><div class="line">	<span class="keyword">var</span> pass=ctx.request.body.password;</div><div class="line">	</div><div class="line">	<span class="comment">// 这里先查找用户名存在与否，存在则判断密码正确与否，不存在就返回false</span></div><div class="line">	<span class="keyword">await</span> userModel.findDataByName(name)</div><div class="line">	 	.then(<span class="function"><span class="params">result</span> =&gt;</span>&#123;</div><div class="line">		 	<span class="comment">// console.log(reslut)</span></div><div class="line">			<span class="keyword">var</span> res=<span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(result))</div><div class="line">			<span class="keyword">if</span> (name === res[<span class="number">0</span>][<span class="string">'name'</span>] &amp;&amp; md5(pass) === res[<span class="number">0</span>][<span class="string">'pass'</span>]) &#123;</div><div class="line">				ctx.body=<span class="string">'true'</span></div><div class="line">				<span class="comment">// ctx.flash.success='登录成功!';</span></div><div class="line">				ctx.session.user=res[<span class="number">0</span>][<span class="string">'name'</span>]</div><div class="line">				ctx.session.id=res[<span class="number">0</span>][<span class="string">'id'</span>]</div><div class="line">				<span class="built_in">console</span>.log(<span class="string">'ctx.session.id'</span>,ctx.session.id)</div><div class="line">				<span class="comment">// ctx.redirect('/posts')</span></div><div class="line">				<span class="built_in">console</span>.log(<span class="string">'session'</span>,ctx.session)</div><div class="line">				<span class="built_in">console</span>.log(<span class="string">'登录成功'</span>)</div><div class="line">			&#125;				</div><div class="line">		 &#125;).catch(<span class="function"><span class="params">err</span>=&gt;</span>&#123;</div><div class="line">		 	ctx.body=<span class="string">'false'</span></div><div class="line">		 	<span class="built_in">console</span>.log(<span class="string">'用户名或密码错误!'</span>)</div><div class="line">		 	<span class="comment">// ctx.redirect('/signin')</span></div><div class="line">		 &#125;)</div><div class="line">&#125;)</div><div class="line"></div><div class="line"><span class="built_in">module</span>.exports=router</div></pre></td></tr></table></figure>
<p>我们进行登录操作，判断登录的用户名和密码是否有误，使用md5加密<br>我们可以看到登录成功返回的结果是<code>result</code> 然后处理一下 var res=JSON.parse(JSON.stringify(result))<br>为什么呢？<br>因为返回的结果是这样的一个数组：id：4 name：rrr  pass：…<br>[ RowDataPacket { id: 4, name: ‘rrr’, pass: ‘44f437ced647ec3f40fa0841041871cd’ } ]</p>
<p>修改views/signin.ejs<br>signin.ejs</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">header</span> %&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"container"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"form create"</span> <span class="attr">method</span>=<span class="string">"post "</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>用户名：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">placeholder</span>=<span class="string">"用户名"</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"name"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">label</span>&gt;</span>密码：<span class="tag">&lt;/<span class="name">label</span>&gt;</span> </div><div class="line">				<span class="tag">&lt;<span class="name">input</span> <span class="attr">placeholder</span>=<span class="string">"密码"</span> <span class="attr">type</span>=<span class="string">"password"</span> <span class="attr">name</span>=<span class="string">"password"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"submit"</span>&gt;</span>登录<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">form</span>&gt;</span>	</div><div class="line">	<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></div><div class="line"><span class="javascript">		$(<span class="string">'.submit'</span>).click(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">			<span class="built_in">console</span>.log($(<span class="string">'.form'</span>).serialize())</span></div><div class="line"><span class="javascript">			$.ajax(&#123;</span></div><div class="line"><span class="javascript">	            url: <span class="string">"/signin"</span>,</span></div><div class="line"><span class="javascript">	            data: $(<span class="string">'.form'</span>).serialize(),</span></div><div class="line"><span class="javascript">	            type: <span class="string">"POST"</span>,</span></div><div class="line"><span class="javascript">	            cache: <span class="literal">false</span>,</span></div><div class="line"><span class="javascript">	            dataType: <span class="string">'json'</span>,</span></div><div class="line"><span class="javascript">	            success: <span class="function"><span class="keyword">function</span> (<span class="params">msg</span>) </span>&#123;</span></div><div class="line"><span class="javascript">	               <span class="keyword">if</span> (!msg) &#123;</span></div><div class="line"><span class="javascript">	               		$(<span class="string">'.error'</span>).text(<span class="string">'用户名或密码错误'</span>)</span></div><div class="line"><span class="javascript">	               		$(<span class="string">'input'</span>).val(<span class="string">''</span>)</span></div><div class="line"><span class="javascript">	               		fade(<span class="string">'.error'</span>)</span></div><div class="line"><span class="undefined">	               &#125;</span></div><div class="line"><span class="javascript">	               <span class="keyword">else</span>&#123;</span></div><div class="line"><span class="javascript">	               		$(<span class="string">'.success'</span>).text(<span class="string">'登录成功'</span>)</span></div><div class="line"><span class="javascript">	               		fade(<span class="string">'.success'</span>)</span></div><div class="line"><span class="javascript">	               		setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">		               		<span class="built_in">window</span>.location.href=<span class="string">"/posts"</span></span></div><div class="line"><span class="undefined">	               		&#125;,1000)    	</span></div><div class="line"><span class="undefined">	               &#125;      </span></div><div class="line"><span class="javascript">	                <span class="comment">//console.log($('.ui.error.message').text);</span></span></div><div class="line"><span class="undefined">	            &#125;,</span></div><div class="line"><span class="javascript">	            error: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></div><div class="line"><span class="javascript">	                alert(<span class="string">'异常'</span>);</span></div><div class="line"><span class="undefined">	            &#125;</span></div><div class="line"><span class="undefined">	        &#125;)</span></div><div class="line"><span class="undefined">			</span></div><div class="line"><span class="undefined">		&#125;)</span></div><div class="line"><span class="undefined">		</span></div><div class="line"><span class="undefined">	</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">footer</span> %&gt;</span></div></pre></td></tr></table></figure>
<p>我们增加了ajax请求，在routers/singin.js里，我们设置如果登录失败就返回false，登录成功返回true<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">ctx.body=&apos;false&apos;</div><div class="line">ctx.body=&apos;true&apos;</div></pre></td></tr></table></figure></p>
<p>那我们登录成功后要做跳转，可以看到<code>window.location.href=&quot;/posts&quot;</code>跳转到posts页面</p>
<h2 id="全部文章"><a href="#全部文章" class="headerlink" title="全部文章"></a>全部文章</h2><p>修改routers/posts.js</p>
<p>posts.js</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> router=<span class="built_in">require</span>(<span class="string">'koa-router'</span>)();</div><div class="line"><span class="comment">// 处理数据库（之前已经写好，在mysql.js）</span></div><div class="line"><span class="keyword">var</span> userModel=<span class="built_in">require</span>(<span class="string">'../lib/mysql.js'</span>)</div><div class="line"><span class="comment">// 时间中间件</span></div><div class="line"><span class="keyword">var</span> moment=<span class="built_in">require</span>(<span class="string">'moment'</span>)</div><div class="line"></div><div class="line"><span class="comment">// get '/'页面</span></div><div class="line">router.get(<span class="string">'/'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	ctx.redirect(<span class="string">'/posts'</span>)</div><div class="line">&#125;)</div><div class="line"><span class="comment">// get '/posts'页面</span></div><div class="line">router.get(<span class="string">'/posts'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="keyword">await</span> ctx.render(<span class="string">'posts'</span>,&#123;</div><div class="line">		session:ctx.session</div><div class="line">	&#125;)</div><div class="line">	</div><div class="line">&#125;)</div><div class="line"><span class="built_in">module</span>.exports=router</div></pre></td></tr></table></figure>
<p>修改 index.js</p>
<p>app.use(require(‘./routers/posts.js’).routes())的注释去掉</p>
<p>修改 views/posts.ejs</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">&lt;% include header %&gt;</div><div class="line"></div><div class="line">	posts</div><div class="line"></div><div class="line">&lt;% include footer %&gt;</div></pre></td></tr></table></figure>
<p>现在看看登录成功之后的页面吧</p>
<p>接下来我们事先登出页面</p>
<h2 id="登出页面"><a href="#登出页面" class="headerlink" title="登出页面"></a>登出页面</h2><p>修改 router/signout.js<br>signout.js</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> router=<span class="built_in">require</span>(<span class="string">'koa-router'</span>)();</div><div class="line"></div><div class="line">router.get(<span class="string">'/signout'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	ctx.session=<span class="literal">null</span>;</div><div class="line">	<span class="built_in">console</span>.log(<span class="string">'登出成功'</span>)</div><div class="line">	ctx.body=<span class="string">'true'</span></div><div class="line">	</div><div class="line">&#125;)</div><div class="line"></div><div class="line"><span class="built_in">module</span>.exports=router</div></pre></td></tr></table></figure>
<p>把session设置为null即可</p>
<p>修改 index.js</p>
<p>app.use(require(‘./routers/posts.js’).routes())的注释去掉，现在把注释的路由全部取消注释就对了</p>
<p>然后修改 views/header.ejs</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">title</span>&gt;</span>koa-blog<span class="tag">&lt;/<span class="name">title</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"stylesheet"</span> <span class="attr">href</span>=<span class="string">"/index.css"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">header</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"user_name"</span>&gt;</span></div><div class="line">			user：</div><div class="line">			<span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(<span class="attr">session.user</span>)&#123; %&gt;</span></div><div class="line">				 <span class="tag">&lt;<span class="name">%=</span> <span class="attr">session.user</span> %&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(!<span class="attr">session.user</span>)&#123; %&gt;</span></div><div class="line">				未登录</div><div class="line">			<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"message"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"error"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"success"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"user_right"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span>  <span class="attr">if</span>(<span class="attr">session.user</span>)&#123; %&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"has_user"</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/posts"</span>&gt;</span>全部文章<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/create"</span>&gt;</span>发表文章<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">span</span> <span class="attr">class</span>=<span class="string">"signout"</span>&gt;</span>登出<span class="tag">&lt;/<span class="name">span</span>&gt;</span></div><div class="line">				<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(!<span class="attr">session.user</span>)&#123; %&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"none_user"</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/posts"</span>&gt;</span>全部文章<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">a</span>  <span class="attr">href</span>=<span class="string">"/signup"</span>&gt;</span>注册<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/signin"</span>&gt;</span>登录<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">				<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">header</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></div><div class="line"><span class="javascript">		<span class="function"><span class="keyword">function</span> <span class="title">fade</span>(<span class="params">data</span>)</span>&#123;</span></div><div class="line"><span class="javascript">			<span class="keyword">if</span> ($(data).css(<span class="string">'display'</span>)!==<span class="string">'none'</span>) &#123;</span></div><div class="line"><span class="javascript">           		$(data).fadeOut(<span class="number">1500</span>)</span></div><div class="line"><span class="undefined">       		&#125;</span></div><div class="line"><span class="javascript">       		<span class="keyword">else</span>&#123;</span></div><div class="line"><span class="javascript">       			$(data).show()</span></div><div class="line"><span class="javascript">           		$(data).fadeOut(<span class="number">1500</span>)</span></div><div class="line"><span class="undefined">       		&#125;</span></div><div class="line"><span class="undefined">		&#125;</span></div><div class="line"><span class="javascript">		$(<span class="string">'.signout'</span>).click(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">			$.ajax(&#123;</span></div><div class="line"><span class="javascript">	            url: <span class="string">"/signout"</span>,</span></div><div class="line"><span class="javascript">	            type: <span class="string">"GET"</span>,</span></div><div class="line"><span class="javascript">	            cache: <span class="literal">false</span>,</span></div><div class="line"><span class="javascript">	            dataType: <span class="string">'json'</span>,</span></div><div class="line"><span class="javascript">	            success: <span class="function"><span class="keyword">function</span> (<span class="params">msg</span>) </span>&#123;</span></div><div class="line"><span class="javascript">	               <span class="keyword">if</span> (msg) &#123;</span></div><div class="line"><span class="javascript">	               		$(<span class="string">'.success'</span>).text(<span class="string">'登出成功'</span>)</span></div><div class="line"><span class="javascript">	               		fade(<span class="string">'.success'</span>)</span></div><div class="line"><span class="javascript">	               		setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">		               		<span class="built_in">window</span>.location.href=<span class="string">"/posts"</span></span></div><div class="line"><span class="undefined">	               		&#125;,1000)      	</span></div><div class="line"><span class="undefined">	               &#125;</span></div><div class="line"><span class="undefined">	            &#125;,</span></div><div class="line"><span class="javascript">	            error: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></div><div class="line"><span class="javascript">	                alert(<span class="string">'异常'</span>);</span></div><div class="line"><span class="undefined">	            &#125;</span></div><div class="line"><span class="undefined">	        &#125;)</span></div><div class="line"><span class="undefined">		&#125;)</span></div><div class="line"><span class="undefined">	</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div></pre></td></tr></table></figure>
<p>增加点击登出后的ajax 的提交，成功之后回到posts页面</p>
<h2 id="发表文章"><a href="#发表文章" class="headerlink" title="发表文章"></a>发表文章</h2><p>修改router/posts<br>在后面增加<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// get '/create'</span></div><div class="line">router.get(<span class="string">'/create'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="keyword">await</span> ctx.render(<span class="string">'create'</span>,&#123;</div><div class="line">		session:ctx.session,</div><div class="line">	&#125;)</div><div class="line">&#125;)</div><div class="line"></div><div class="line"><span class="comment">// psot '/create'</span></div><div class="line">router.post(<span class="string">'/create'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	</div><div class="line">	<span class="built_in">console</span>.log(ctx.session.user)	</div><div class="line">	<span class="keyword">var</span> title=ctx.request.body.title</div><div class="line">	<span class="keyword">var</span> content=ctx.request.body.content</div><div class="line">	<span class="keyword">var</span> id=ctx.session.id</div><div class="line">	<span class="keyword">var</span> name=ctx.session.user</div><div class="line">	<span class="keyword">var</span> time=moment().format(<span class="string">'YYYY-MM-DD HH:mm'</span>)</div><div class="line">	<span class="built_in">console</span>.log([name,title,content,id,time])</div><div class="line">	<span class="comment">// 这里我们向数据库插入用户名、标题、内容、发表文章用户的id、时间，成功返回true，失败为false</span></div><div class="line">	<span class="keyword">await</span> userModel.insertPost([name,title,content,id,time])</div><div class="line">		.then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</div><div class="line">			ctx.body=<span class="string">'true'</span></div><div class="line">		&#125;).catch(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</div><div class="line">			ctx.body=<span class="string">'false'</span></div><div class="line">		&#125;)</div><div class="line">&#125;)</div></pre></td></tr></table></figure></p>
<p>修改 views/create.ejs</p>
<p>create.ejs</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">header</span> %&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"container"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">form</span> <span class="attr">method</span>=<span class="string">"post"</span> <span class="attr">class</span>=<span class="string">"form create"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">label</span>&gt;</span>标题：<span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">input</span> <span class="attr">placeholder</span>=<span class="string">""</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"title"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">label</span>&gt;</span>内容：<span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">textarea</span> <span class="attr">name</span>=<span class="string">"content"</span> <span class="attr">id</span>=<span class="string">""</span> <span class="attr">cols</span>=<span class="string">"42"</span> <span class="attr">rows</span>=<span class="string">"10"</span>&gt;</span><span class="tag">&lt;/<span class="name">textarea</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"submit"</span>&gt;</span>发表<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">form</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span>	</div><div class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></div><div class="line"><span class="javascript">	$(<span class="string">'.submit'</span>).click(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">		$.ajax(&#123;</span></div><div class="line"><span class="javascript">            url: <span class="string">"/create"</span>,</span></div><div class="line"><span class="javascript">            data: $(<span class="string">'.form'</span>).serialize(),</span></div><div class="line"><span class="javascript">            type: <span class="string">"POST"</span>,</span></div><div class="line"><span class="javascript">            cache: <span class="literal">false</span>,</span></div><div class="line"><span class="javascript">            dataType: <span class="string">'json'</span>,</span></div><div class="line"><span class="javascript">            success: <span class="function"><span class="keyword">function</span> (<span class="params">msg</span>) </span>&#123;</span></div><div class="line"><span class="javascript">               <span class="keyword">if</span> (msg) &#123;</span></div><div class="line"><span class="javascript">               		$(<span class="string">'.success'</span>).text(<span class="string">'发表成功'</span>)</span></div><div class="line"><span class="javascript">               		fade(<span class="string">'.success'</span>)</span></div><div class="line"><span class="javascript">               		setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">	               		<span class="built_in">window</span>.location.href=<span class="string">"/posts"</span></span></div><div class="line"><span class="undefined">               		&#125;,1000)</span></div><div class="line"><span class="javascript">               &#125;<span class="keyword">else</span>&#123;</span></div><div class="line"><span class="javascript">                  $(<span class="string">'.success'</span>).text(<span class="string">'发表失败'</span>)</span></div><div class="line"><span class="javascript">                  fade(<span class="string">'.success'</span>)</span></div><div class="line"><span class="javascript">                  setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">                    <span class="built_in">window</span>.location.reload()</span></div><div class="line"><span class="undefined">                  &#125;,1000)</span></div><div class="line"><span class="undefined">               &#125;</span></div><div class="line"><span class="undefined">            &#125;,</span></div><div class="line"><span class="javascript">            error: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></div><div class="line"><span class="javascript">                alert(<span class="string">'异常'</span>);</span></div><div class="line"><span class="undefined">            &#125;</span></div><div class="line"><span class="undefined">        &#125;)			</span></div><div class="line"><span class="undefined">	&#125;)</span></div><div class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">footer</span> %&gt;</span></div></pre></td></tr></table></figure>
<p>现在看看能不能发表吧</p>
<p>即使我们发表了文章，但是当前我们的posts的页面没有显示，因为还没有获取到数据</p>
<p>接下来</p>
<p>修改 routers/posts.js</p>
<p>修改 get ‘/posts’</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line">router.get(<span class="string">'/posts'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	</div><div class="line">	<span class="comment">// 这里我们先通过查找有没有类似/posts?author=XXX 的连接跳转，如果有就执行下面这句话，把用户名取下来，由于用户名存在中文，所以我们进行解码</span></div><div class="line">	<span class="keyword">if</span> (ctx.request.querystring) &#123;</div><div class="line">		<span class="built_in">console</span>.log(<span class="string">'ctx.request.querystring'</span>,<span class="built_in">decodeURIComponent</span>(ctx.request.querystring.split(<span class="string">'='</span>)[<span class="number">1</span>]))</div><div class="line">		<span class="keyword">await</span> userModel.findDataByUser(<span class="built_in">decodeURIComponent</span>(ctx.request.querystring.split(<span class="string">'='</span>)[<span class="number">1</span>]))</div><div class="line">			.then(<span class="function"><span class="params">result</span>=&gt;</span>&#123;</div><div class="line">				res=<span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(result))</div><div class="line">				<span class="built_in">console</span>.log(res)</div><div class="line">			&#125;)</div><div class="line">		<span class="keyword">await</span> ctx.render(<span class="string">'posts'</span>,&#123;</div><div class="line">				session:ctx.session,</div><div class="line">				posts:res	</div><div class="line">			&#125;)</div><div class="line">	&#125;<span class="keyword">else</span>&#123;</div><div class="line">		<span class="comment">// 如果连接是正常的 如 /posts 则我们获取的是全部文章的列表，所以通过findAllPost查找全部文章并向模板传递数据posts， posts的值为res</span></div><div class="line">		<span class="keyword">await</span> userModel.findAllPost()</div><div class="line">			.then(<span class="function"><span class="params">result</span>=&gt;</span>&#123;</div><div class="line">				<span class="built_in">console</span>.log(result)</div><div class="line">				res=<span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(result)) </div><div class="line">				<span class="built_in">console</span>.log(<span class="string">'post'</span>,res)</div><div class="line">			&#125;)</div><div class="line">		<span class="keyword">await</span> ctx.render(<span class="string">'posts'</span>,&#123;</div><div class="line">			session:ctx.session,</div><div class="line">			posts:res	</div><div class="line">		&#125;)</div><div class="line">	&#125;</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>if (ctx.request.querystring) {}这部分我们先不用管，后面会说。只需要看else后面的代码我们查找我们发表的全部文章然后将获取到的值定义为posts，传给模板posts.ejs，这样就可以渲染出来了</p>
<p>修改 Views/posts.ejs</p>
<p>posts.ejs</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">header</span> %&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">"posts"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">%</span> <span class="attr">posts.forEach</span>(<span class="attr">function</span>(<span class="attr">res</span>)&#123; %&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">li</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"post_3"</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">p</span> <span class="attr">class</span>=<span class="string">"post_user"</span>&gt;</span><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/posts?author=&lt;%= res['name'] %&gt;"</span>&gt;</span>作者: <span class="tag">&lt;<span class="name">%=</span> <span class="attr">res</span>['<span class="attr">name</span>'] %&gt;</span><span class="tag">&lt;/<span class="name">a</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">p</span> <span class="attr">class</span>=<span class="string">"post_comments"</span>&gt;</span>评论数：<span class="tag">&lt;<span class="name">%=</span> <span class="attr">res</span>['<span class="attr">comments</span>'] %&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">p</span> <span class="attr">class</span>=<span class="string">"post_pv"</span>&gt;</span>浏览数：<span class="tag">&lt;<span class="name">%=</span> <span class="attr">res</span>['<span class="attr">pv</span>'] %&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">				<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/posts/&lt;%= res['id'] %&gt;"</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"post_title"</span>&gt;</span></div><div class="line">						<span class="tag">&lt;<span class="name">h3</span>&gt;</span>title<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></div><div class="line">						<span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">%=</span> <span class="attr">res</span>['<span class="attr">title</span>'] %&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">					<span class="tag">&lt;/<span class="name">div</span>&gt;</span>	</div><div class="line">					<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"post_content"</span>&gt;</span></div><div class="line">						<span class="tag">&lt;<span class="name">h3</span>&gt;</span>content<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></div><div class="line">						<span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">%=</span> <span class="attr">res</span>['<span class="attr">content</span>'] %&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">					<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;/<span class="name">a</span>&gt;</span>		</div><div class="line">				<span class="tag">&lt;<span class="name">p</span> <span class="attr">class</span>=<span class="string">"post_time"</span>&gt;</span>发表时间：<span class="tag">&lt;<span class="name">%=</span> <span class="attr">res</span>['<span class="attr">moment</span>'] %&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">li</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">%</span> &#125;) %&gt;</span>	</div><div class="line">	<span class="tag">&lt;/<span class="name">ul</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">footer</span> %&gt;</span></div></pre></td></tr></table></figure>
<p>现在看看posts页面有没有文章出现了</p>
<p>我们看到是所有的文章，但是我需要点击单篇文章的时候，显示一篇文章怎么办呢？</p>
<p>修改 routers/posts.js</p>
<p>在posts.js后面增加</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">router.get(<span class="string">'/posts/:postId'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="built_in">console</span>.log(ctx.params.postId)</div><div class="line">	<span class="comment">// 通过文章id查找返回数据，然后增加pv 浏览 +1 </span></div><div class="line">	<span class="keyword">await</span> userModel.findDataById(ctx.params.postId)</div><div class="line">		.then(<span class="function"><span class="params">result</span>=&gt;</span>&#123;</div><div class="line">				res=<span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(result))</div><div class="line">				res_pv=<span class="built_in">parseInt</span>(<span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(result))[<span class="number">0</span>][<span class="string">'pv'</span>])</div><div class="line">				res_pv+=<span class="number">1</span></div><div class="line">				<span class="built_in">console</span>.log(res)</div><div class="line">			&#125;)</div><div class="line">	</div><div class="line">	<span class="comment">// 渲染模板，并传递三个数据		</span></div><div class="line">	<span class="keyword">await</span> ctx.render(<span class="string">'sPost'</span>,&#123;</div><div class="line">				session:ctx.session,</div><div class="line">				posts:res</div><div class="line">			&#125;)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>现在的设计是，我们点进去出现的url是 /posts/1 这类的 1代表该篇文章的id，我们在数据库建表的时候就处理了，让id为主键，然后递增</p>
<p>我们通过userModel.findDataById 文章的id来查找数据库<br>我们通过userModel.findCommentById 文章的id来查找文章的评论，因为单篇文章里面有评论的功能</p>
<h2 id="单篇文章页"><a href="#单篇文章页" class="headerlink" title="单篇文章页"></a>单篇文章页</h2><p>修改 views/sPost.ejs</p>
<p>sPost.ejs</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">header</span> %&gt;</span>	</div><div class="line">	<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"spost"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">p</span> <span class="attr">class</span>=<span class="string">"spost_user"</span>&gt;</span>author: <span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/posts?author=&lt;%= posts[0]['name'] %&gt;"</span>&gt;</span><span class="tag">&lt;<span class="name">%=</span> <span class="attr">posts</span>[<span class="attr">0</span>]['<span class="attr">name</span>'] %&gt;</span><span class="tag">&lt;/<span class="name">a</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"post_title"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">h3</span>&gt;</span>title<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/posts/&lt;%= posts[0]['id'] %&gt;"</span>&gt;</span><span class="tag">&lt;<span class="name">%=</span> <span class="attr">posts</span>[<span class="attr">0</span>]['<span class="attr">title</span>'] %&gt;</span><span class="tag">&lt;/<span class="name">a</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"post_content"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">h3</span>&gt;</span>content<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">%=</span> <span class="attr">posts</span>[<span class="attr">0</span>]['<span class="attr">content</span>'] %&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"edit"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(<span class="attr">session</span> &amp;&amp; <span class="attr">session.user</span>===  <span class="string">posts[0][</span>'<span class="attr">name</span>']  )&#123; %&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"&lt;%= posts[0]['id'] %&gt;/edit"</span>&gt;</span>编辑<span class="tag">&lt;/<span class="name">a</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">a</span> <span class="attr">class</span>=<span class="string">"delete_post"</span> &gt;</span>删除<span class="tag">&lt;/<span class="name">a</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></div><div class="line"><span class="javascript">				$(<span class="string">'.delete_post'</span>).click(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">					$.ajax(&#123;</span></div><div class="line"><span class="javascript">						url:<span class="string">"&lt;%= posts[0]['id'] %&gt;/remove"</span>,</span></div><div class="line"><span class="javascript">						type:<span class="string">'GET'</span>,</span></div><div class="line"><span class="javascript">						cache: <span class="literal">false</span>,</span></div><div class="line"><span class="javascript">						success:<span class="function"><span class="keyword">function</span>(<span class="params">msg</span>)</span>&#123;</span></div><div class="line"><span class="javascript">							<span class="keyword">if</span> (msg.data==<span class="number">1</span>) &#123;</span></div><div class="line"><span class="javascript">								$(<span class="string">'.success'</span>).text(<span class="string">'删除文章成功'</span>)</span></div><div class="line"><span class="javascript">               					fade(<span class="string">'.success'</span>)</span></div><div class="line"><span class="javascript">               					setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">					               		<span class="built_in">window</span>.location.href=<span class="string">"/posts"</span>	</span></div><div class="line"><span class="undefined">               					&#125;,1000)</span></div><div class="line"><span class="javascript">							&#125;<span class="keyword">else</span> <span class="keyword">if</span>(msg.data==<span class="number">2</span>)&#123;</span></div><div class="line"><span class="javascript">								$(<span class="string">'.error'</span>).text(<span class="string">'删除文章失败'</span>)</span></div><div class="line"><span class="javascript">               					fade(<span class="string">'.error'</span>);</span></div><div class="line"><span class="javascript">               					setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">	               					<span class="built_in">window</span>.location.reload()</span></div><div class="line"><span class="undefined">               					&#125;,1000)</span></div><div class="line"><span class="undefined">							&#125;</span></div><div class="line"><span class="undefined">						&#125;</span></div><div class="line"><span class="undefined">					&#125;)</span></div><div class="line"><span class="undefined">				&#125;)</span></div><div class="line"><span class="undefined">			</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"comment_wrap"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">h3</span>&gt;</span>comment<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"comment_list"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> <span class="attr">comments.forEach</span>(<span class="attr">function</span>(<span class="attr">res</span>)&#123; %&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"cmt_lists"</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">p</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">					<span class="tag">&lt;<span class="name">p</span> <span class="attr">class</span>=<span class="string">"cmt_content"</span>&gt;</span></div><div class="line">						content: <span class="tag">&lt;<span class="name">%=</span> <span class="attr">res</span>['<span class="attr">content</span>'] %&gt;</span></div><div class="line">						<span class="tag">&lt;<span class="name">span</span> <span class="attr">class</span>=<span class="string">"cmt_name"</span>&gt;</span></div><div class="line">							By: <span class="tag">&lt;<span class="name">%=</span> <span class="attr">res</span>['<span class="attr">name</span>'] %&gt;</span></div><div class="line">							<span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(<span class="attr">session</span> &amp;&amp; <span class="attr">session.user</span> ===  <span class="string">res[</span>'<span class="attr">name</span>']  )&#123; %&gt;</span></div><div class="line">								<span class="tag">&lt;<span class="name">a</span> <span class="attr">class</span>=<span class="string">"delete_comment"</span>&gt;</span> 删除<span class="tag">&lt;/<span class="name">a</span>&gt;</span></div><div class="line">							<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">						<span class="tag">&lt;/<span class="name">span</span>&gt;</span></div><div class="line">					<span class="tag">&lt;/<span class="name">p</span>&gt;</span></div><div class="line">				<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></div><div class="line"><span class="javascript">					$(<span class="string">'.delete_comment'</span>).click(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">						$.ajax(&#123;</span></div><div class="line"><span class="xml">							url:"<span class="tag">&lt;<span class="name">%=</span> <span class="attr">posts</span>[<span class="attr">0</span>]['<span class="attr">id</span>'] %&gt;</span>/comment/<span class="tag">&lt;<span class="name">%=</span> <span class="attr">res</span>['<span class="attr">id</span>'] %&gt;</span>/remove",</span></div><div class="line"><span class="javascript">							type:<span class="string">'GET'</span>,</span></div><div class="line"><span class="javascript">							cache: <span class="literal">false</span>,</span></div><div class="line"><span class="javascript">							success:<span class="function"><span class="keyword">function</span>(<span class="params">msg</span>)</span>&#123;</span></div><div class="line"><span class="javascript">								<span class="keyword">if</span> (msg.data==<span class="number">1</span>) &#123;</span></div><div class="line"><span class="javascript">									$(<span class="string">'.success'</span>).text(<span class="string">'删除留言成功'</span>)</span></div><div class="line"><span class="javascript">	               					fade(<span class="string">'.success'</span>)</span></div><div class="line"><span class="javascript">	               					setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">		               					<span class="built_in">window</span>.location.reload()</span></div><div class="line"><span class="undefined">	               					&#125;,1000)</span></div><div class="line"><span class="javascript">								&#125;<span class="keyword">else</span> <span class="keyword">if</span>(msg.data==<span class="number">2</span>)&#123;</span></div><div class="line"><span class="javascript">									$(<span class="string">'.error'</span>).text(<span class="string">'删除留言失败'</span>)</span></div><div class="line"><span class="javascript">	               					fade(<span class="string">'.error'</span>);</span></div><div class="line"><span class="javascript">	               					setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">		               					<span class="built_in">window</span>.location.reload()</span></div><div class="line"><span class="undefined">	               					&#125;,1000)</span></div><div class="line"><span class="undefined">								&#125;</span></div><div class="line"><span class="undefined">							&#125;,</span></div><div class="line"><span class="javascript">							error:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></div><div class="line"><span class="javascript">								alert(<span class="string">'异常'</span>)</span></div><div class="line"><span class="undefined">							&#125;</span></div><div class="line"><span class="undefined">						&#125;)</span></div><div class="line"><span class="undefined">					&#125;)</span></div><div class="line"><span class="undefined">				</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">%</span> &#125;) %&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span>	</div><div class="line">		<span class="tag">&lt;<span class="name">%</span> <span class="attr">if</span>(<span class="attr">session.user</span>)&#123; %&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"form"</span> <span class="attr">method</span>=<span class="string">"post"</span> <span class="attr">action</span>=<span class="string">"/&lt;%= posts[0]['id'] %&gt;"</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">textarea</span> <span class="attr">name</span>=<span class="string">"content"</span> <span class="attr">id</span>=<span class="string">""</span>&gt;</span><span class="tag">&lt;/<span class="name">textarea</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"submit"</span>&gt;</span>发表留言<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">form</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">%</span> &#125; %&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></div><div class="line"><span class="javascript">		$(<span class="string">'.submit'</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span></div><div class="line"><span class="javascript">			$.ajax(&#123;</span></div><div class="line"><span class="javascript">	            url: <span class="string">'/'</span>+<span class="built_in">document</span>.URL.slice(<span class="built_in">document</span>.URL.lastIndexOf(<span class="string">'/'</span>)+<span class="number">1</span>),</span></div><div class="line"><span class="javascript">	            data:$(<span class="string">'.form'</span>).serialize(),</span></div><div class="line"><span class="javascript">	            type: <span class="string">"POST"</span>,</span></div><div class="line"><span class="javascript">	            cache: <span class="literal">false</span>,</span></div><div class="line"><span class="javascript">	            dataType: <span class="string">'json'</span>,</span></div><div class="line"><span class="javascript">	            success: <span class="function"><span class="keyword">function</span> (<span class="params">msg</span>) </span>&#123;</span></div><div class="line"><span class="javascript">	               <span class="keyword">if</span> (msg) &#123;</span></div><div class="line"><span class="javascript">	               		$(<span class="string">'.success'</span>).text(<span class="string">'发表留言成功'</span>)</span></div><div class="line"><span class="javascript">	               		fade(<span class="string">'.success'</span>)</span></div><div class="line"><span class="javascript">	               		setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">		               		<span class="built_in">window</span>.location.reload()</span></div><div class="line"><span class="undefined">	               		&#125;,1000)  	</span></div><div class="line"><span class="undefined">	               &#125;</span></div><div class="line"><span class="undefined">	            &#125;,</span></div><div class="line"><span class="javascript">	            error: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></div><div class="line"><span class="javascript">	                alert(<span class="string">'异常'</span>);</span></div><div class="line"><span class="undefined">	            &#125;</span></div><div class="line"><span class="undefined">	        &#125;)</span></div><div class="line"><span class="undefined">		&#125;)</span></div><div class="line"><span class="undefined">	</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span>	</div><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">footer</span> %&gt;</span></div></pre></td></tr></table></figure>
<p>现在点击单篇文章试试，进入单篇文章页面，但是编辑、删除、评论都还没有做，点击无效，我们先不做，先实现每个用户发表的文章列表，我们之前在 get ‘/posts’ 里面说先忽略if (ctx.request.querystring) {}里面的代码，这里是做了应该处理，假如用户点击了某个用户，该用户发表了几篇文章，我们需要只显示该用户发表的文章，那么进入的url应该是 /posts?author=xxx ,这个处理在posts.ejs 就已经加上了，就在文章的左下角，作者：xxx就是一个链接。我们通过判断用户来查找文章，继而有了<code>ctx.request.querystring</code> 获取到的是：<code>author=XXX</code></p>
<p>注：这里我们处理了，通过判断 <code>session.user ===  res[&#39;name&#39;]</code> 如果不是该用户发的文章，不能编辑和删除，评论也是。这里面也可以注意一下包裹的<code>&lt;a href=&quot;&quot;&gt;&lt;/a&gt;</code>标签</p>
<h2 id="编辑文章、删除文章、评论、删除评论"><a href="#编辑文章、删除文章、评论、删除评论" class="headerlink" title="编辑文章、删除文章、评论、删除评论"></a>编辑文章、删除文章、评论、删除评论</h2><blockquote>
<p>评论</p>
</blockquote>
<p>修改routers/posts.js </p>
<p>在post.js 后面增加</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line">router.post(<span class="string">'/:postId'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="keyword">var</span> name=ctx.session.user</div><div class="line">	<span class="keyword">var</span> content=ctx.request.body.content</div><div class="line">	<span class="keyword">var</span> postId=ctx.params.postId</div><div class="line">	</div><div class="line">	<span class="comment">// 插入评论的用户名，内容和文章id</span></div><div class="line">	<span class="keyword">await</span> userModel.insertComment([name,content,postId])</div><div class="line">	<span class="comment">// 先通过文章id查找，然后评论数+1</span></div><div class="line">	<span class="keyword">await</span> userModel.findDataById(postId)</div><div class="line">			.then(<span class="function"><span class="params">result</span>=&gt;</span>&#123;</div><div class="line">				res_comments=<span class="built_in">parseInt</span>(<span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(result))[<span class="number">0</span>][<span class="string">'comments'</span>])</div><div class="line">				res_comments+=<span class="number">1</span></div><div class="line">			&#125;)</div><div class="line">	<span class="comment">// 更新评论数 res_comments</span></div><div class="line">	<span class="keyword">await</span> userModel.updatePostComment([res_comments,postId])</div><div class="line">		.then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</div><div class="line">			ctx.body=<span class="string">'true'</span></div><div class="line">		&#125;).catch(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</div><div class="line">			ctx.body=<span class="string">'false'</span></div><div class="line">		&#125;)	</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>现在试试发表评论的功能吧，之所以这样简单，因为我们之前就在sPost.ejs做了好几个ajax的处理，删除文章和评论也是如此</p>
<blockquote>
<p>删除评论</p>
</blockquote>
<p>修改routers/posts.js </p>
<p>继续在post.js 后面增加</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line">router.get(<span class="string">'/posts/:postId/comment/:commentId/remove'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	</div><div class="line">	<span class="keyword">var</span> postId=ctx.params.postId</div><div class="line">	<span class="keyword">var</span> commentId=ctx.params.commentId</div><div class="line">	<span class="keyword">await</span> userModel.findDataById(postId)</div><div class="line">			.then(<span class="function"><span class="params">result</span>=&gt;</span>&#123;</div><div class="line">				res_comments=<span class="built_in">parseInt</span>(<span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(result))[<span class="number">0</span>][<span class="string">'comments'</span>])</div><div class="line">				<span class="built_in">console</span>.log(<span class="string">'res'</span>,res_comments)</div><div class="line">				res_comments-=<span class="number">1</span></div><div class="line">				<span class="built_in">console</span>.log(res_comments)</div><div class="line">			&#125;)</div><div class="line">	<span class="keyword">await</span> userModel.updatePostComment([res_comments,postId])</div><div class="line">	<span class="keyword">await</span> userModel.deleteComment(commentId)</div><div class="line">		.then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</div><div class="line">			 ctx.body=&#123;</div><div class="line">			 	data:<span class="number">1</span></div><div class="line">			 &#125;</div><div class="line">		&#125;).catch(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</div><div class="line">			  ctx.body=&#123;</div><div class="line">			 	data:<span class="number">2</span></div><div class="line">			 &#125;</div><div class="line">		&#125;)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>现在试试删除评论的功能吧</p>
<blockquote>
<p>删除文章</p>
</blockquote>
<p>只有自己发表的文字删除的文字才会显示出来，才能被删除，</p>
<p>修改routers/posts.js </p>
<p>继续在post.js 后面增加</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">router.get(<span class="string">'/posts/:postId/remove'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	</div><div class="line">	<span class="keyword">var</span> postId=ctx.params.postId</div><div class="line">	</div><div class="line">	<span class="keyword">await</span> userModel.deleteAllPostComment(postId)</div><div class="line">	<span class="keyword">await</span> userModel.deletePost(postId)</div><div class="line">		.then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</div><div class="line">			 ctx.body=&#123;</div><div class="line">			 	data:<span class="number">1</span></div><div class="line">			 &#125;	</div><div class="line">		&#125;).catch(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</div><div class="line">			ctx.body=&#123;</div><div class="line">			 	data:<span class="number">2</span></div><div class="line">			 &#125;</div><div class="line">		&#125;)</div><div class="line">	</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>现在试试删除文章的功能吧</p>
<blockquote>
<p>编辑文字</p>
</blockquote>
<p>修改routers/posts.js </p>
<p>继续在post.js 后面增加</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// get '/posts/:postId/edit'</span></div><div class="line">router.get(<span class="string">'/posts/:postId/edit'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="keyword">var</span> name=ctx.session.user</div><div class="line">	<span class="keyword">var</span> postId=ctx.params.postId</div><div class="line">	</div><div class="line">	<span class="keyword">await</span> userModel.findDataById(postId)</div><div class="line">		.then(<span class="function"><span class="params">result</span>=&gt;</span>&#123;</div><div class="line">			res=<span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(result))</div><div class="line">			<span class="built_in">console</span>.log(<span class="string">'修改文章'</span>,res)</div><div class="line">		&#125;)</div><div class="line">	<span class="keyword">await</span> ctx.render(<span class="string">'edit'</span>,&#123;</div><div class="line">			session:ctx.session,</div><div class="line">			posts:res</div><div class="line">		&#125;)</div><div class="line">&#125;)</div><div class="line"><span class="comment">// post '/posts/:postId/edit'</span></div><div class="line">router.post(<span class="string">'/posts/:postId/edit'</span>,<span class="keyword">async</span> (ctx,next)=&gt;&#123;</div><div class="line">	<span class="keyword">var</span> title=ctx.request.body.title</div><div class="line">	<span class="keyword">var</span> content=ctx.request.body.content</div><div class="line">	<span class="keyword">var</span> id=ctx.session.id</div><div class="line">	<span class="keyword">var</span> postId=ctx.params.postId</div><div class="line">		</div><div class="line">	<span class="keyword">await</span> userModel.updatePost([title,content,postId])</div><div class="line">		.then(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</div><div class="line">			ctx.body=<span class="string">'true'</span></div><div class="line">		&#125;).catch(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</div><div class="line">			ctx.body=<span class="string">'false'</span></div><div class="line">		&#125;)</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<p>修改views/edit.js </p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">header</span> %&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"container"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"form create"</span> <span class="attr">method</span>=<span class="string">"post"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">label</span>&gt;</span>标题：<span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">input</span> <span class="attr">placeholder</span>=<span class="string">"标题"</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"title"</span> <span class="attr">value</span>=<span class="string">"&lt;%= posts[0]['title'] %&gt;"</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">label</span>&gt;</span>内容：<span class="tag">&lt;/<span class="name">label</span>&gt;</span></div><div class="line">			<span class="tag">&lt;<span class="name">textarea</span> <span class="attr">name</span>=<span class="string">"content"</span> <span class="attr">id</span>=<span class="string">""</span> <span class="attr">cols</span>=<span class="string">"42"</span> <span class="attr">rows</span>=<span class="string">"10"</span>&gt;</span></div><div class="line">				<span class="tag">&lt;<span class="name">%=</span> <span class="attr">posts</span>[<span class="attr">0</span>]['<span class="attr">content</span>'] %&gt;</span></div><div class="line">			<span class="tag">&lt;/<span class="name">textarea</span>&gt;</span></div><div class="line">		<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">		<span class="comment">&lt;!-- &lt;input type="submit" value="修改"&gt; --&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"submit"</span>&gt;</span>修改<span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">form</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></div><div class="line"><span class="javascript">	$(<span class="string">'.submit'</span>).click(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">		$.ajax(&#123;</span></div><div class="line"><span class="javascript">            url: <span class="built_in">document</span>.URL,</span></div><div class="line"><span class="javascript">            data: $(<span class="string">'.form'</span>).serialize(),</span></div><div class="line"><span class="javascript">            type: <span class="string">"POST"</span>,</span></div><div class="line"><span class="javascript">            cache: <span class="literal">false</span>,</span></div><div class="line"><span class="javascript">            dataType: <span class="string">'json'</span>,</span></div><div class="line"><span class="javascript">            success: <span class="function"><span class="keyword">function</span> (<span class="params">msg</span>) </span>&#123;</span></div><div class="line"><span class="javascript">               <span class="keyword">if</span> (msg) &#123;</span></div><div class="line"><span class="javascript">               		$(<span class="string">'.success'</span>).text(<span class="string">'修改成功'</span>)</span></div><div class="line"><span class="javascript">               		fade(<span class="string">'.success'</span>)</span></div><div class="line"><span class="javascript">               		setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span></div><div class="line"><span class="javascript">	               		<span class="built_in">window</span>.location.href=<span class="string">"/posts"</span></span></div><div class="line"><span class="undefined">               		&#125;,1000)</span></div><div class="line"><span class="undefined">               &#125;</span></div><div class="line"><span class="undefined">            &#125;,</span></div><div class="line"><span class="javascript">            error: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span></div><div class="line"><span class="javascript">                alert(<span class="string">'异常'</span>);</span></div><div class="line"><span class="undefined">            &#125;</span></div><div class="line"><span class="undefined">        &#125;)	</span></div><div class="line"><span class="undefined">	&#125;)</span></div><div class="line"><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">%</span> <span class="attr">include</span> <span class="attr">footer</span> %&gt;</span></div></pre></td></tr></table></figure>
<p>现在试试编辑文字然后修改提交吧</p>
<h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2><p>至此一个简单的blog就已经制作好了，其他扩展功能相信你已经会了吧！如果出现问题，还望积极提问哈，我会尽快处理的</p>
<p>所有的代码都在 <a href="https://github.com/wclimb/Koa2-blog" target="_blank" rel="external">https://github.com/wclimb/Koa2-blog</a> 里面，如果觉得不错就star一下吧。有问题可以提问哟<br>下一篇可能是 Node + express + mongoose 或 zepto源码系列<br>感谢您的阅读^_^</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/原创/" rel="tag"># 原创</a>
          
            <a href="/tags/Node/" rel="tag"># Node</a>
          
            <a href="/tags/Koa/" rel="tag"># Koa</a>
          
            <a href="/tags/Mysql/" rel="tag"># Mysql</a>
          
            <a href="/tags/javascript/" rel="tag"># javascript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/06/29/读zepto源码，封装自己的zepto库（一）/" rel="next" title="读zepto源码，封装自己的zepto库（一）">
                <i class="fa fa-chevron-left"></i> 读zepto源码，封装自己的zepto库（一）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/07/17/读zepto源码，封装自己的zepto库（二）/" rel="prev" title="读zepto源码，封装自己的zepto库（二）">
                读zepto源码，封装自己的zepto库（二） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="wclimb" />
          <p class="site-author-name" itemprop="name">wclimb</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">7</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/wclimb" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/3966368179" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.lukedever.cn" title="Lukedever" target="_blank">Lukedever</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Koa2-blog"><span class="nav-number">1.</span> <span class="nav-text">Koa2-blog</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#预览地址"><span class="nav-number">2.</span> <span class="nav-text">预览地址</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#写在前面"><span class="nav-number">3.</span> <span class="nav-text">写在前面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#演示效果"><span class="nav-number">4.</span> <span class="nav-text">演示效果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开发环境"><span class="nav-number">5.</span> <span class="nav-text">开发环境</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#准备工作"><span class="nav-number">6.</span> <span class="nav-text">准备工作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#目录结构"><span class="nav-number">7.</span> <span class="nav-text">目录结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#首先配置config"><span class="nav-number">8.</span> <span class="nav-text">首先配置config</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置index-js文件"><span class="nav-number">9.</span> <span class="nav-text">配置index.js文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置lib的mysql-js文件"><span class="nav-number">10.</span> <span class="nav-text">配置lib的mysql.js文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现注册页面"><span class="nav-number">11.</span> <span class="nav-text">实现注册页面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#完善注册功能"><span class="nav-number">12.</span> <span class="nav-text">完善注册功能</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模板引擎ejs"><span class="nav-number">13.</span> <span class="nav-text">模板引擎ejs</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#登录页面"><span class="nav-number">14.</span> <span class="nav-text">登录页面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#全部文章"><span class="nav-number">15.</span> <span class="nav-text">全部文章</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#登出页面"><span class="nav-number">16.</span> <span class="nav-text">登出页面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#发表文章"><span class="nav-number">17.</span> <span class="nav-text">发表文章</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#单篇文章页"><span class="nav-number">18.</span> <span class="nav-text">单篇文章页</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#编辑文章、删除文章、评论、删除评论"><span class="nav-number">19.</span> <span class="nav-text">编辑文章、删除文章、评论、删除评论</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number">20.</span> <span class="nav-text">结语</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wclimb</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

<span id="showDays"></span>
<script>
var birthDay = new Date("6/27/2017");
var now = new Date();
var duration = now.getTime() - birthDay.getTime();
var total= Math.floor(duration / (1000 * 60 * 60 * 24));
document.getElementById("showDays").innerHTML = "本站已运行 "+total+" 天";
</script>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>  访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
